Robbie Hatley's Solutions, in Perl, for The Weekly Challenge #295 ("Recursive Segmentation")

For those not familiar with "The Weekly Challenge", it is a weekly programming puzzle with two parts, cycling every Sunday. You can find it here:

The Weekly Challenge

The Weekly Challenge for the week of 2024-11-10 through 2024-11-16 is #295.

The tasks for challenge #295 are as follows:

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Task 295-1: Word Break
Submitted by: Mohammad Sajid Anwar
Write a script to return true-or-false depending on whether-
or-not a given string can be segmented into a sequence of
one-or-more words from a given list of words.

Example 1:
Input:  string = 'weeklychallenge'   words = ("challenge", "weekly")
Output: true

Example 2

Input:  string = 'perlrakuperl'      words = ("raku", "perl")
Output: true

Example 3

Input:  string = 'sonsanddaughters'  words = ("sons", "sand", "daughters")
Output: false

This problem (like the second) lends itself to solution by recursion. My recursive subroutine first segments the string into two non-empty fragments, using every possible first-segment length. For each first segment which is in the list, send the corresponding second segment back through the subroutine, in a process of "recursive segmentation".

Robbie Hatley's Perl Solution to The Weekly Challenge 295-1

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Task 295-2: Jump Game
Submitted by: Mohammad Sajid Anwar
Write a script to find the minimum number of jumps to reach from
the first element to the last of a given array of integers,
@ints, such that $ints[$i] represents the maximum length of a
forward jump from the index $i. If the last element is
unreachable, then return -1.

Example 1:
Input:  @ints = (2, 3, 1, 1, 4)
Output: 2
Jump 1 step from index 0 then 3 steps from index 1 to the last
element.

Example 2:
Input:  @ints = (2, 3, 0, 4)
Output: 2

Example 3:
Input:  @ints = (2, 0, 0, 4)
Output: -1

This problem (like the first) lends itself to solution by recursion. My recursive subroutine first jumps every allowable distance forward from the current position. Then for each new position it lands on, it sends the corresponding new start location and jumps-so-far back through the subroutine, in a process of "recursive segmentation".

Robbie Hatley's Perl Solution to The Weekly Challenge 295-2

That's it for challenge 295; see you on challenge 296!

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