Duplicates and triplets
Weekly challenge 234 — 11 September 2023
Week 234 - 11.09.2023
You are given an array of words made up of alphabetic characters only. Write a script to return all alphabetic characters that show up in all words including duplicates.
Now we can be sure that any letters that appear in all the words must appear in $words. So let's iterate over the letters in $words, and see if they appear in $words etc. Any that do, we add to our list of common characters.
But there is a complication, which is that we need to allow for repeated letters.
The first way round this is for our iteration not just to be over individual characters but over sequences of the same character, which I've called samples. So in our 'javascipt' example, first we check that sample 'aa' appears in all the words, then 'c' and so on.
But that still doesn't quite work, because while 'julia' doesn't contain 'aa', it does contain 'a'. So for every sample in $words which is more than 1 character we need to check shorter versions. So in our example, after checking 'aa' we need to check 'a'.
And that's my algorithm. Note especially the
while ($sample) loop
$sample =~ s|.||; at the end to repeatedly shorten the sample by one character
until it's empty.
The content of this website is licensed by Peter Campbell Smith under a Creative Commons Attribution 4.0 International Licence