Robbie Hatley's Perl Solutions To The Weekly Challenge #205
For those not familiar with "The Weekly Challenge", it is a weekly programming puzzle, usually with two parts, cycling every Sunday. You can find it here:
This week (2023-02-19 through 2023-02-25) is weekly challenge #205.
Task 1 is to write a script which returns the 3rd-highest unique value found in an array of ints, or the max value if the array contains fewer than 3 unique values. I found this perhaps the easiest Weekly-Challenge task I've ever done; it can be solved in 3 lines:
my @unique = uniqint reverse sort @array;
if (@unique >= 3) {say "Third-highest unique value = $unique[2]"}
else {say "Maximum unique value = $unique[0]"}}
Task 2 is "Write a script to find the highest value obtained by XORing any two distinct members of an array of non-negative integers" (to paraphrase). This one I found slightly trickier. I use a pair of nested 3-part loops:
ARRAY: for (@arrays){
say '';
my @array = @{$_};
say "Array: (@array)";
for (@array) {if ($_<0) {say "Error: negative integer found!"; next ARRAY;}}
my $curxor = 0;
my $maxxor = 0;
for ( my $i = 0 ; $i <= $#array - 1 ; ++$i ) {
for ( my $j = $i + 1 ; $i <= $#array - 0 ; ++$i ) {
$curxor = $array[$i] ^ $array[$j];
if ($curxor > $maxxor) {$maxxor = $curxor}}}
say "max xor = $maxxor"}
That's it for 205; see you on 206.
Comments
Post a Comment