The weekly challenge 268 - Task 1: Magic Number
1 #!/usr/bin/perl 2 # https://theweeklychallenge.org/blog/perl-weekly-challenge-268/#TASK1 3 # 4 # Task 1: Magic Number 5 # ==================== 6 # 7 # You are given two arrays of integers of same size, @x and @y. 8 # 9 # Write a script to find the magic number that when added to each elements of 10 # one of the array gives the second array. Elements order is not important. 11 # 12 # Example 1 13 # 14 # Input: @x = (3, 7, 5) 15 # @y = (9, 5, 7) 16 # Output: 2 17 # 18 # The magic number is 2. 19 # @x = (3, 7, 5) 20 # + 2 2 2 21 # @y = (5, 9, 7) 22 # 23 # Example 2 24 # 25 # Input: @x = (1, 2, 1) 26 # @y = (5, 4, 4) 27 # Output: 3 28 # 29 # The magic number is 3. 30 # @x = (1, 2, 1) 31 # + 3 3 3 32 # @y = (5, 4, 4) 33 # 34 # Example 3 35 # 36 # Input: @x = (2) 37 # @y = (5) 38 # Output: 3 39 # 40 ############################################################ 41 ## 42 ## discussion 43 ## 44 ############################################################ 45 # 46 # By sorting both arrays, we have each element in each array paired up 47 # with the corresponding element of the other array, so the magic number 48 # is the difference from one element in one array to its corresponding 49 # element in the other array. We can even use this for a sanity check: 50 # if the elements don't match up at some point, then no magic number 51 # exists 52 53 use strict; 54 use warnings; 55 56 magic_number( [3, 7, 5], [9, 5, 7] ); 57 magic_number( [1, 2, 1], [5, 4, 4] ); 58 magic_number( [2], [5] ); 59 60 sub magic_number { 61 my ($x, $y) = @_; 62 print "Input: (", join(", ", @$x), "), (", join(", ", @$y), ")\n"; 63 my @sorted_x = sort { $a <=> $b } @$x; 64 my @sorted_y = sort { $a <=> $b } @$y; 65 die "Both arrays don't have the same length!" unless scalar(@sorted_x) == scalar(@sorted_y); 66 my $magic = $sorted_y[0] - $sorted_x[0]; 67 foreach my $idx (0..$#sorted_x) { 68 die "There is no magic number that works for all elements of both arrays!" unless $sorted_x[$idx] + $magic == $sorted_y[$idx]; 69 } 70 print "Output: $magic\n"; 71 } 72