perl logo Perl logo (Thanks to Olaf Alders)

The weekly challenge 390 - Task 1: Decode String

 1 #!/usr/bin/env perl
 2 # https://theweeklychallenge.org/blog/perl-weekly-challenge-390/#TASK1
 3 #
 4 # Task 1: Decode String
 5 # =====================
 6 #
 7 # You are given an encoded string.
 8 #
 9 # Write a script to return the decoded string of the given encoded string.
10 #
11 ##    The encoding rule is: K[encoded_string], where the encoded_string inside
12 ##    the square brackets is repeated exactly K > 0 times.
13 #
14 ## Example 1
15 ##
16 ## Input: $str = "2[3[a]]"
17 ## Output: "aaaaaa"
18 ##
19 ## 3[a]    => aaa
20 ## 2[3[a]] => aaa aaa
21 #
22 ## Example 2
23 ##
24 ## Input: $str = "10[a]"
25 ## Output: "aaaaaaaaaa"
26 #
27 ## Example 3
28 ##
29 ## Input: $str = "a2[b]c3[d]e"
30 ## Output: "abbcddde"
31 #
32 ## Example 4
33 ##
34 ## Input: $str = "2[a2[b]c]"
35 ## Output: "abbcabbc"
36 #
37 ## Example 5
38 ##
39 ## Input: $str = "1[a]2[b3[c]]"
40 ## Output: "abcccbccc"
41 #
42 ############################################################
43 ##
44 ## discussion
45 ##
46 ############################################################
47 #
48 # We replace all K[str] parts from the inside out by making sure
49 # we have only strings without any [ or ] inside. The rest is
50 # just perl's amazing s///e in action so we can call a function
51 # to calculate the replacement in each step.
52 
53 use v5.36;
54 
55 decode_string("2[3[a]]");
56 decode_string("10[a]");
57 decode_string("a2[b]c3[d]e");
58 decode_string("2[a2[b]c]");
59 decode_string("1[a]2[b3[c]]");
60 
61 sub decode_string($str) {
62     say "Input: \"$str\"";
63     while($str =~ m/\[/) {
64         $str =~ s/(\d+)\[([^\[\]]*)\]/dec("$1","$2")/e;
65     }
66     say "Output: \"$str\"";
67 }
68 
69 sub dec($count, $str) {
70     my $result = "";
71     while($count-- > 0) {
72         $result .= $str;
73     }
74     return $result;
75 }