1 #!/usr/bin/perl 2 # https://theweeklychallenge.org/blog/perl-weekly-challenge-205/#TASK2 3 # 4 # Maximum XOR 5 # =========== 6 # 7 # You are given an array of integers. 8 # 9 # Write a script to find the highest value obtained by XORing any two distinct members of the array. 10 # 11 ## Example 1 12 ## 13 ## Input: @array = (1,2,3,4,5,6,7) 14 ## Output: 7 15 ## 16 ## The maximum result of 1 xor 6 = 7. 17 # 18 ## Example 2 19 ## 20 ## Input: @array = (2,4,1,3) 21 ## Output: 7 22 ## 23 ## The maximum result of 4 xor 3 = 7. 24 # 25 ## Example 3 26 ## 27 ## Input: @array = (10,5,7,12,8) 28 ## Output: 15 29 ## 30 ## The maximum result of 10 xor 5 = 15. 31 # 32 ############################################################ 33 ## 34 ## discussion 35 ## 36 ############################################################ 37 # 38 # We have to walk the array in two loops to get all combinations 39 # of elements, then we xor those elements and remember the 40 # maximum result. 41 42 use strict; 43 use warnings; 44 45 maximum_xor(1,2,3,4,5,6,7); 46 maximum_xor(2,4,1,3); 47 maximum_xor(10,5,7,12,8); 48 maximum_xor(); 49 maximum_xor(1); 50 51 sub maximum_xor { 52 my @array = @_; 53 # just some error handling for when the array is too small 54 if(@array < 2) { 55 print "Not enough elements in array to calculate xor!\n"; 56 return; 57 } 58 print "Input: (" . join(", ", @array) . ")\n"; 59 # initialize the maximum with the xor of the first two elements 60 my $max = ($array[0] ^ $array[1]); 61 foreach my $i (0..$#array) { 62 foreach my $j ($i+1..$#array) { 63 my $now = ($array[$i] ^ $array[$j]); 64 $max = $now if $now > $max; 65 } 66 } 67 print "Output: $max\n"; 68 }