perl logo Perl logo (Thanks to Olaf Alders)

The weekly challenge 369 - Task 2: Group Division

 1 #!/usr/bin/env perl
 2 # https://theweeklychallenge.org/blog/perl-weekly-challenge-369/#TASK2
 3 #
 4 # Task 2: Group Division
 5 # ======================
 6 #
 7 # You are given a string, group size and filler character.
 8 #
 9 # Write a script to divide the string into groups of given size. In the last
10 # group if the string doesn’t have enough characters remaining fill with the
11 # given filler character.
12 #
13 ## Example 1
14 ##
15 ## Input: $str = "RakuPerl", $size = 4, $filler = "*"
16 ## Output: ("Raku", "Perl")
17 #
18 ## Example 2
19 ##
20 ## Input: $str = "Python", $size = 5, $filler = "0"
21 ## Output: ("Pytho", "n0000")
22 #
23 ## Example 3
24 ##
25 ## Input: $str = "12345", $size = 3, $filler = "x"
26 ## Output: ("123", "45x")
27 #
28 ## Example 4
29 ##
30 ## Input: $str = "HelloWorld", $size = 3, $filler = "_"
31 ## Output: ("Hel", "loW", "orl", "d__")
32 #
33 ## Example 5
34 ##
35 ## Input: $str = "AI", $size = 5, $filler = "!"
36 ## Output: "AI!!!"
37 #
38 ############################################################
39 ##
40 ## discussion
41 ##
42 ############################################################
43 #
44 # As long as $str still has a positive length, we capture the first
45 # up to $size characters in a temporary string, set $str to the
46 # remainder after removing that part, and fill up the temporary
47 # string with $filler as needed. We keep all of these strings
48 # in an array so we can print it in the end.
49 
50 use v5.36;
51 
52 group_division("RakuPerl", 4, "*");
53 group_division("Python", 5, "0");
54 group_division("12345", 3, "x");
55 group_division("HelloWorld", 3, "_");
56 group_division("AI", 5, "!");
57 
58 sub group_division($str, $size, $filler) {
59     say "Input: \$str = \"$str\", \$size = $size, \$filler = \"$filler\"";
60     my @result = ();
61     while(length($str)) {
62         my $tmp = substr($str, 0, $size);
63         $str = length($str) >= $size ? substr($str, $size) : "";
64         my $len = $size - length($tmp);
65         $tmp .= $filler x $len if $len;
66         push @result, $tmp;
67     }
68     say "Output: (\"" . join("\", \"", @result) . "\")";
69 }