The weekly challenge 316 - Task 1: Circular
1 #!/usr/bin/env perl 2 # https://theweeklychallenge.org/blog/perl-weekly-challenge-316/#TASK1 3 # 4 # Task 1: Circular 5 # ================ 6 # 7 # You are given a list of words. 8 # 9 # Write a script to find out whether the last character of each word is the 10 # first character of the following word. 11 # 12 ## Example 1 13 ## 14 ## Input: @list = ("perl", "loves", "scala") 15 ## Output: true 16 # 17 # 18 ## Example 2 19 ## 20 ## Input: @list = ("love", "the", "programming") 21 ## Output: false 22 # 23 # 24 ## Example 3 25 ## 26 ## Input: @list = ("java", "awk", "kotlin", "node.js") 27 ## Output: true 28 # 29 ############################################################ 30 ## 31 ## discussion 32 ## 33 ############################################################ 34 # 35 # For each element of the list, we pick the first and last character. 36 # If the last character of the previous element matches the first, 37 # everything is still fine and we go to the next element. If there's a 38 # mismatch, we can jump out of the loop right away and return false. 39 # At the end, we can return true. 40 # For the first element, we initialize the "previous last character" 41 # as the first character of the first list element so we don't fall 42 # out of the loop prematurely. 43 44 use v5.36; 45 circular("perl", "loves", "scala"); 46 circular("love", "the", "programming"); 47 circular("java", "awk", "kotlin", "node.js"); 48 49 sub circular(@list) { 50 say "Input: (\"" . join("\", \"", @list) . ")"; 51 my $prev_char = substr($list[0], 0, 1); 52 foreach my $elem (@list) { 53 my $first = substr($elem, 0, 1); 54 my $last = substr($elem, length($elem) - 1, 1); 55 if($first ne $prev_char) { 56 return say "Output: false"; 57 } 58 $prev_char = $last; 59 } 60 say "Output: true"; 61 }