The weekly challenge 268 - Task 2: Number Game

 1 #!/usr/bin/perl
 2 # https://theweeklychallenge.org/blog/perl-weekly-challenge-268/#TASK2
 3 #
 4 # Task 2: Number Game
 5 # ===================
 6 #
 7 # You are given an array of integers, @ints, with even number of elements.
 8 #
 9 # Write a script to create a new array made up of elements of the given array.
10 # Pick the two smallest integers and add it to new array in decreasing order
11 # i.e. high to low. Keep doing until the given array is empty.
12 #
13 ## Example 1
14 ##
15 ## Input: @ints = (2, 5, 3, 4)
16 ## Output: (3, 2, 5, 4)
17 ##
18 ## Round 1: we picked (2, 3) and push it to the new array (3, 2)
19 ## Round 2: we picked the remaining (4, 5) and push it to the new array (5, 4)
20 #
21 ## Example 2
22 ##
23 ## Input: @ints = (9, 4, 1, 3, 6, 4, 6, 1)
24 ## Output: (1, 1, 4, 3, 6, 4, 9, 6)
25 #
26 ## Example 3
27 ##
28 ## Input: @ints = (1, 2, 2, 3)
29 ## Output: (2, 1, 3, 2)
30 #
31 ############################################################
32 ##
33 ## discussion
34 ##
35 ############################################################
36 #
37 # First, we sort the input array. Then we pick the first two elements
38 # in reverse order until there are no more elements in the array.
39 
40 use strict;
41 use warnings;
42 
43 number_game(2, 5, 3, 4);
44 number_game(9, 4, 1, 3, 6, 4, 6, 1);
45 number_game(1, 2, 2, 3);
46 
47 sub number_game {
48    my @ints = @_;
49    print "Input: (", join(", ", @ints), ")\n";
50    my @sorted = sort { $a <=> $b } @ints;
51    my @result = ();
52    while(scalar(@sorted) >= 2) {
53       my $first = shift @sorted;
54       my $second = shift @sorted;
55       push @result, ($second, $first);
56    }
57    print "Output: (", join(", ", @result), ")\n";
58 }
59