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

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-01-29 through 2023-02-04) is weekly challenge #202.

Task 1 I found super easy: "You are given an array of integers. Write a script to print 1 if there are 3 consecutive odds in the given array; otherwise print 0." The sub I wrote to do that was just a few simple lines which I wrote in 5 minutes flat:

sub tco (@a){
   for (my $i = 0 ; $i <= $#a-2 ; ++$i){
      if ( !($a[$i+0]%2) ) {$i += 0; next;}
      if ( !($a[$i+1]%2) ) {$i += 1; next;}
      if ( !($a[$i+2]%2) ) {$i += 2; next;}
      return 1;}
   return 0;}

Task 2, however, I found much more challenging: "Given a profile as a list of altitudes, return the leftmost widest valley. A valley is defined as a subarray of the profile consisting of two parts: the first part is non-increasing and the second part is non-decreasing. Either part can be empty."

Yikes. My solution to that took me several hours, with much debugging and refactoring. I ended up having to use a finite state machine, complicated by the fact that any flat ground is simultaneously part of the right wall of the valley to its left and part of the left wall of the valley to its right. My code is too lengthy to cut-n-paste in this blog, but see here:

Robbie's Solution to 202-2

That's it for 202; looking forward to 203.

Comments

Popular posts from this blog

Robbie Hatley's Solutions To The Weekly Challenge #262

Robbie Hatley's Solutions To The Weekly Challenge #266

Robbie Hatley's Solutions To The Weekly Challenge #273