The weekly challenge 318 - Task 1: Group Position
1 #!/usr/bin/env perl 2 # https://theweeklychallenge.org/blog/perl-weekly-challenge-318/#TASK1 3 # 4 # Task 1: Group Position 5 # ====================== 6 # 7 # You are given a string of lowercase letters. 8 # 9 # Write a script to find the position of all groups in the given string. Three 10 # or more consecutive letters form a group. Return "” if none found. 11 # 12 ## Example 1 13 ## 14 ## Input: $str = "abccccd" 15 ## Output: "cccc" 16 # 17 # 18 ## Example 2 19 ## 20 ## Input: $str = "aaabcddddeefff" 21 ## Output: "aaa", "dddd", "fff" 22 # 23 # 24 ## Example 3 25 ## 26 ## Input: $str = "abcdd" 27 ## Output: "" 28 # 29 ############################################################ 30 ## 31 ## discussion 32 ## 33 ############################################################ 34 # 35 # We need to remember the last character and any already existing 36 # substring of $str that consists of only the same character. 37 # If the current character matches the last one, we just add it to 38 # the temporary string. If it doesn't match, we reset $lastchar and 39 # the temporary string to the current character. In the end, we also 40 # capture the current $tmpstr and add it to the result list in case it's 41 # longer than or equal to 3 characters. 42 43 use v5.36; 44 45 group_position("abccccd"); 46 group_position("aaabcddddeefff"); 47 group_position("abcdd"); 48 49 sub group_position($str) { 50 say "Input: \"$str\""; 51 my @result = (); 52 53 my $tmpstr = ""; 54 my $lastchar = ""; 55 my @chars = split//, $str; 56 foreach my $char (@chars) { 57 if($char eq $lastchar) { 58 $tmpstr .= $char; 59 } else { 60 if(length($tmpstr) > 2) { 61 push @result, $tmpstr; 62 } 63 $tmpstr = $char; 64 $lastchar = $char; 65 } 66 } 67 if(length($tmpstr) > 2) { 68 push @result, $tmpstr; 69 } 70 71 say "Output: \"" . join("\", \"", @result) . "\""; 72 }