Peter
Peter Campbell Smith

Magic and scrambled numbers

Weekly challenge 268 — 6 May 2024

Week 268 - 6 May 2024

Task 2

Task — Number game

You are given an array of integers, @ints, with an even number of elements. Write a script to create a new array made up of elements of the given array. Pick the two smallest integers and add it to new array in decreasing order i.e. high to low. Keep doing until the given array is empty.

Examples


Example 1
Input: @ints = (2, 5, 3, 4)
Output: (3, 2, 5, 4)

Round 1: we picked (2, 3) and push it to the new 
  array (3, 2)
Round 2: we picked the remaining (4, 5) and push it to 
  the new array (5, 4)

Example 2
Input: @ints = (9, 4, 1, 3, 6, 4, 6, 1)
Output: (1, 1, 4, 3, 6, 4, 9, 6)

Example 3
Input: @ints = (1, 2, 2, 3)
Output: (2, 1, 3, 2)

Analysis

Someone will have a one-liner for this, but I did it the easy way:

  • Sort @ints,
  • repeatedly pull off elements ($a and $b) of the sorted array, and
  • push them onto @to in the order $b, $a.

Try it 

Try running the script with any input:



example: 3, 1, 4, 1, 5, 9, 2, 6, 5, 4

Script


#!/usr/bin/perl

# Blog: http://ccgi.campbellsmiths.force9.co.uk/challenge

use v5.26;    # The Weekly Challenge - 2024-05-06
use utf8;     # Week 268 - task 2 - Number game
use warnings; # Peter Campbell Smith
binmode STDOUT, ':utf8';

number_game(2, 5, 3, 4);
number_game(9, 4, 1, 3, 6, 4, 6, 1);
number_game(1, 2, 2, 3);
number_game(1, 7, 6, 0, 2, 3, 5, 7, 1, 3, 9, 3, 4, 7, 7, 2, 0, 8);

sub number_game {
    
    my ($j, @from, @to);
    
    # sort the input
    @from = sort {$a <=> $b} @_;
    
    # add the input 2 by 2 to the output
    for ($j = 0; $j < @from; $j += 2) {
        push @to, $from[$j + 1], $from[$j];
    }
    
    # show the answer
    say sprintf(qq[\nInput:  \@ints = (%s)], join(', ', @_));
    say sprintf(qq[Output:         (%s)], join(', ', @to));
}

Output


Input:  @ints = (2, 5, 3, 4)
Output:         (3, 2, 5, 4)

Input:  @ints = (9, 4, 1, 3, 6, 4, 6, 1)
Output:         (1, 1, 4, 3, 6, 4, 9, 6)

Input:  @ints = (1, 2, 2, 3)
Output:         (2, 1, 3, 2)

Input:  @ints = (1, 7, 6, 0, 2, 3, 5, 7, 1, 3, 9, 3, 4, 7, 7, 2, 0, 8)
Output:         (0, 0, 1, 1, 2, 2, 3, 3, 4, 3, 6, 5, 7, 7, 7, 7, 9, 8)