The weekly challenge 362 - Task 1: Echo Chamber
1 #!/usr/bin/env perl 2 # https://theweeklychallenge.org/blog/perl-weekly-challenge-362/#TASK1 3 # 4 # Task 1: Echo Chamber 5 # ==================== 6 # 7 ## Example 1 8 ## 9 ## Input: "abca" 10 ## Output: "abbcccaaaa" 11 ## 12 ## Index 0: "a" -> repeated 1 time -> "a" 13 ## Index 1: "b" -> repeated 2 times -> "bb" 14 ## Index 2: "c" -> repeated 3 times -> "ccc" 15 ## Index 3: "a" -> repeated 4 times -> "aaaa" 16 # 17 # 18 ## Example 2 19 ## 20 ## Input: "xyz" 21 ## Output: "xyyzzz" 22 ## 23 ## Index 0: "x" -> "x" 24 ## Index 1: "y" -> "yy" 25 ## Index 2: "z" -> "zzz" 26 # 27 # 28 ## Example 3 29 ## 30 ## Input: "code" 31 ## Output: "coodddeeee" 32 ## 33 ## Index 0: "c" -> "c" 34 ## Index 1: "o" -> "oo" 35 ## Index 2: "d" -> "ddd" 36 ## Index 3: "e" -> "eeee" 37 # 38 # 39 ## Example 4 40 ## 41 ## Input: "hello" 42 ## Output: "heelllllllooooo" 43 ## 44 ## Index 0: "h" -> "h" 45 ## Index 1: "e" -> "ee" 46 ## Index 2: "l" -> "lll" 47 ## Index 3: "l" -> "llll" 48 ## Index 4: "o" -> "ooooo" 49 # 50 # 51 ## Example 5 52 ## 53 ## Input: "a" 54 ## Output: "a" 55 ## 56 ## Index 0: "a" -> "a" 57 # 58 ############################################################ 59 ## 60 ## discussion 61 ## 62 ############################################################ 63 # 64 # We pick every character and add it to the output the appropriate 65 # amount of times. 66 67 use v5.36; 68 69 echo_chamber("abca"); 70 echo_chamber("xyz"); 71 echo_chamber("code"); 72 echo_chamber("hello"); 73 echo_chamber("a"); 74 75 sub echo_chamber($str) { 76 say "Input: $str"; 77 my @chars = split //, $str; 78 my $out = ""; 79 foreach my $i (1..$#chars+1) { 80 $out .= $chars[$i-1] x $i; 81 } 82 say "Output: $out"; 83 } 84