Tricky characters
Weekly challenge 316 — 7 April 2025
Week 316: 7 Apr 2025
You are given a @list
of words.
Write a script to find out whether the last character of each word is the first character of the following word.
Example 1 Input: @list = ('perl', 'loves', 'scala') Output: true Example 2 Input: @list = ('love', 'the', 'programming') Output: false Example 3 Input: @list = ('java', 'awk', 'kotlin', 'node.js') Output: true
There are (at least) two ways to approach this challenge.
Firstly, it could be done as a one-liner.
Secondly it could be done my way, which has two advantages:
Of course there is nothing in the rules of the challenge to say that the supplied answer should be especially efficient or maintainable, but in real life these are probably reasonable goals.
My solution does a single pass over the words, comparing the last letter of each to the first letter of the next. At the first mismatch, it documents the issue and returns from the function. If the loop completes without finding a mismatch, then the list of words complies with the stated condition.
You could criticise my approach in that it will return 'yes' for a list containing just one word, or even no words. This is because my code applies an 'innocent unless proved guilty' approach, and those edge cases are deemed innocent because they don't contain a clash between a last and a first letter. In a production environment I'd want the client to specify what should happen in such cases, and I would provide for that in the code.
#!/usr/bin/perl # Blog: http://ccgi.campbellsmiths.force9.co.uk/challenge use v5.26; # The Weekly Challenge - 2025-04-07 use utf8; # Week 316 - task 1 - Circular use warnings; # Peter Campbell Smith binmode STDOUT, ':utf8'; use Encode; circular('perl', 'loves', 'scala'); circular('love', 'eggs', 'scrambled'); circular('love', 'scrambled', 'eggs'); circular(qw[koala antelope elephant tiger rhino ostrich hen narwhal leopard donkey yak]); circular(qw[the elegant tawny yak kicks slippery fish]); sub circular { my (@list, $j); #initialise @list = @_; say qq[\nInput: \@list = ('] . join(q[', '], @list) . q[')]; # check for compliance for $j (0.. $#list - 1) { if (substr($list[$j], -1, 1) ne substr($list[$j + 1], 0, 1)) { say qq[Output: no - '$list[$j]' and '$list[$j + 1]']; return; } } # no problems say qq[Output: yes]; }
Input: @list = ('perl', 'loves', 'scala') Output: yes Input: @list = ('love', 'eggs', 'scrambled') Output: yes Input: @list = ('love', 'scrambled', 'eggs') Output: no - 'love' and 'scrambled' Input: @list = ('koala', 'antelope', 'elephant', 'tiger', 'rhino', 'ostrich', 'hen', 'narwhal', 'leopard', 'donkey', 'yak') Output: yes Input: @list = ('the', 'elegant', 'tawny', 'yak', 'kicks', 'slippery', 'fish') Output: no - 'slippery' and 'fish'
Any content of this website which has been created by Peter Campbell Smith is in the public domain