Robbie Hatley's Solutions, in Perl, for The Weekly Challenge #296 ("String Compression & Matchstick Squares")
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 for the week of 2024-11-17 through 2024-11-23 is #296.
The tasks for challenge #296 are as follows:
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Task 296-1: String Compression Submitted by: Mohammad Sajid Anwar You are given a string of alphabetic characters, $chars. Write a script to compress the string with run-length encoding, as shown in the examples. A compressed unit can be either a single character or a count followed by a character. BONUS: Write a decompression function. Example 1: Input: $chars = "abbc" Output: "a2bc" Example 2: Input: $chars = "aaabccc" Output: "3ab3c" Example 3: Input: $chars = "abcc" Output: "ab2c"
Since this problem involves an input consisting of a string of characters processed in left-to-right order, we need only keep track of the "current character" and begin point of the previous segment, where a "segment" is a contiguous block of 1-or-more identical characters. Each time we reach the beginning of a new segment (or the one-past-end index), the length of the previous segment will be index - prev. Then set prev = index and move to the next character, until all segment lengths (and their characters) have been determined. Each segment will be written to the compressed string as "length followed by character" (except for segments of length 1, which will be written as just the character).
Robbie Hatley's Perl Solution to The Weekly Challenge 296-1
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Task 296-2: Matchstick Square Submitted by: Mohammad Sajid Anwar You are given an array of integers, @ints. Write a script to find if it is possible to make one square using the sticks as in the given array @ints where $ints[i] is the length of ith stick. Example 1 Input: @ints = (1, 2, 2, 2, 1) Output: true Top: $ints[1] = 2 Bottom: $ints[2] = 2 Left: $ints[3] = 2 Right: $ints[0] and $ints[4] = 2 Example 2 Input: @ints = (2, 2, 2, 4) Output: false Example 3 Input: @ints = (2, 2, 2, 2, 4) Output: false Example 4 Input: @ints = (3, 4, 1, 4, 3, 1) Output: true
This problem essentially asks if a set of integers can be partitioned into 4 partitions with the sums of the integers in the 4 partitions being equal. To reduce headaches and complexity, I'll use CPAN module Algorithm::Combinatorics for the partitionings. (See file ch-2-old.pl for a "manual" version of this program, and file ch-2.pl for my new "automated" version of this program.)
OLD solution image:
Robbie Hatley's Perl OLD Solution to The Weekly Challenge 296-2
NEW solution image:
Robbie Hatley's Perl NEW Solution to The Weekly Challenge 296-2
That's it for challenge 296; see you on challenge 297!
Comments
Post a Comment