Posts

Showing posts from February, 2023

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: The Weekly Challenge 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 ...

Robbie Hatley's Perl Solutions To The Weekly Challenge #204

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: The Weekly Challenge This week (2023-02-12 through 2023-02-18) is weekly challenge #204. Task 1 is "determine if an array is monotonic". This is just a matter of using the "&&=", "<=", and ">=" operators: sub is_mono (@a){ my $mono; $mono = 1; for ( my $i = 1 ; $i <= $#a ; ++$i ){ $mono &&= ($a[$i-1]<=$a[$i]);} # mono inc? if ( $mono == 1 ) {return 1;} $mono = 1; for ( my $i = 1 ; $i <= $#a ; ++$i ){ $mono &&= ($a[$i-1]>=$a[$i]);} # mono dec? if ( $mono == 1 ) {return 2;} return 0;} Task 2 is "reshape array". The approach I took was to first note the original shape, then record the elements in a flat array, then note the desired shape, then reshape if possible: sub shape { my $r = sh...

Robbie Hatley's Perl Solutions To The Weekly Challenge #203

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: The Weekly Challenge This week (2023-02-05 through 2023-02-11) is weekly challenge #203. Task 1 I found absurdly simple: Write a script to determine the number of "Special Quadruplets" in any given array of integers. Given an array "nums" of integers, a "Special Quadruplet" is a slice nums[a,b,c,d] that satisfies the following 2 rules: 1) nums[a] + nums[b] + nums[c] == nums[d] 2) a < b < c < d That had "quadruple nested for loops" written all over it, so that's just what I did: for (@arrays){ my @nums = @{$_}; my @quads = (); my ($a, $b, $c, $d) = (0,0,0,0); for ( $a = 0 ; $a <= $#nums - 3 ; ++$a ){ for ( $b = $a + 1 ; $b <= $#nums - 2 ; ++$b ){ for ( $c = $b + 1 ; $c <= $#nums - 1 ; ++$c ){ ...