The weekly challenge 286 - Task 2: Order Game
1 #!/usr/bin/env perl 2 # https://theweeklychallenge.org/blog/perl-weekly-challenge-286/#TASK2 3 # 4 # Task 2: Order Game 5 # ================== 6 # 7 # You are given an array of integers, @ints, whose length is a power of 2. 8 # 9 # Write a script to play the order game (min and max) and return the last element. 10 # 11 ## Example 1 12 ## 13 ## Input: @ints = (2, 1, 4, 5, 6, 3, 0, 2) 14 ## Output: 1 15 ## 16 ## Operation 1: 17 ## 18 ## min(2, 1) = 1 19 ## max(4, 5) = 5 20 ## min(6, 3) = 3 21 ## max(0, 2) = 2 22 ## 23 ## Operation 2: 24 ## 25 ## min(1, 5) = 1 26 ## max(3, 2) = 3 27 ## 28 ## Operation 3: 29 ## 30 ## min(1, 3) = 1 31 # 32 ## Example 2 33 ## 34 ## Input: @ints = (0, 5, 3, 2) 35 ## Output: 0 36 ## 37 ## Operation 1: 38 ## 39 ## min(0, 5) = 0 40 ## max(3, 2) = 3 41 ## 42 ## Operation 2: 43 ## 44 ## min(0, 3) = 0 45 # 46 ## Example 3 47 ## 48 ## Input: @ints = (9, 2, 1, 4, 5, 6, 0, 7, 3, 1, 3, 5, 7, 9, 0, 8) 49 ## Output: 2 50 ## 51 ## Operation 1: 52 ## 53 ## min(9, 2) = 2 54 ## max(1, 4) = 4 55 ## min(5, 6) = 5 56 ## max(0, 7) = 7 57 ## min(3, 1) = 1 58 ## max(3, 5) = 5 59 ## min(7, 9) = 7 60 ## max(0, 8) = 8 61 ## 62 ## Operation 2: 63 ## 64 ## min(2, 4) = 2 65 ## max(5, 7) = 7 66 ## min(1, 5) = 1 67 ## max(7, 8) = 8 68 ## 69 ## Operation 3: 70 ## 71 ## min(2, 7) = 2 72 ## max(1, 8) = 8 73 ## 74 ## Operation 4: 75 ## 76 ## min(2, 8) = 2 77 # 78 ############################################################ 79 ## 80 ## discussion 81 ## 82 ############################################################ 83 # 84 # As long as @ints has more than one element, replace it with 85 # an array that contains the min/max of each pair of numbers, 86 # properly switching from min to max and vice versa on each 87 # step. 88 89 use strict; 90 use warnings; 91 use List::Util qw(min max); 92 93 order_game(2, 1, 4, 5, 6, 3, 0, 2); 94 order_game(0, 5, 3, 2); 95 order_game(9, 2, 1, 4, 5, 6, 0, 7, 3, 1, 3, 5, 7, 9, 0, 8); 96 97 sub order_game { 98 my @ints = @_; 99 print "Input: (" . join(", ", @ints) . ")\n"; 100 while(scalar(@ints) > 1) { 101 @ints = min_max(@ints); 102 } 103 print "Output: $ints[0]\n"; 104 } 105 106 sub min_max { 107 my @ints = @_; 108 my @result = (); 109 my $which = 0; 110 for (my $i = 0; $i < $#ints; $i+=2) { 111 if($which) { 112 $which = 0; 113 push @result, max($ints[$i], $ints[$i+1]); 114 } else { 115 $which = 1; 116 push @result, min($ints[$i], $ints[$i+1]); 117 } 118 } 119 return @result; 120 }