RabbitFarm
2024-11-25
String Together a Square
The examples used here are from the weekly challenge problem statement and demonstrate the working solution.
Part 1: String Compression
You are given a string of alphabetic characters, $chars. Write a script to compress the string with run-length encoding.
A compressed unit can be either a single character or a count followed by a character.
BONUS: Write a decompression function.
After working so much with recursion for the previous challenge, TWC 295, this time around we’ll use a simple loop mechanism available in Perl: a redo block.
The main loop for iterating over the characters one by one.
Here’s a subroutine which co-ordinates encoding: splits the string, invokes the loop, and returns the compressed format.
The BONUS seems to be fairly doable. Given an encoded string we can expand it back to the original by a similar process as the encoding. In fact, let’s use the same sort of loop.
As before we’ll define a subroutine which co-ordinates decoding.
Putting it all together...
The rest of the code just runs some simple tests.
-
MAIN:{
say encoding q/abbc/;
say encoding q/aaabccc/;
say encoding q/abcc/;
say q//;
say decoding encoding q/abbc/;
say decoding encoding q/aaabccc/;
say decoding encoding q/abcc/;
}
◇
-
Fragment referenced in 6.
Sample Run
$ perl perl/ch-1.pl a2bc 3ab3c ab2c abbc aaabccc abcc
Part 2: Matchstick Square
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.
First let’s notice that the lengths must all sum to a number evenly divisible by four, so that’ll be an initial filter on the list. If that first test passes we divide the sum by four (to get the side length) and determine if we can get four subsets which all sum to that side length.
If we have a sum of lengths evenly divisible by four we’ll then check if if we have four subsets which sum to the computed side length. To do this we’ll compute the powerset (all subsets) of the list and check the sums.
The rest of the code drives some tests.
-
MAIN:{
say boolean is_square 1, 2, 2, 2, 1;
say boolean is_square 2, 2, 2, 4;
say boolean is_square 2, 2, 2, 2, 4;
say boolean is_square 3, 4, 1, 4, 3, 1;
}
◇
-
Fragment referenced in 12.
Sample Run
$ perl perl/ch-2.pl 1 0 0 1
References
posted at: 00:31 by: Adam Russell | path: /perl | permanent link to this entry