Common characters and
squareful sequences
Weekly challenge 220 — 5 June 2023
Week 220: 5 Jun 2023
You are given a list of words. Write a script to return the list of characters (sorted alphabetically) found in every word of the given list.
The simplest way to do this, I think is to start with $word[0] and then delete from it every
character not found in each other word, like this:
for $w (1 .. scalar @words - 1) {
$words[0] =~ s|[^$words[$w]]||gi;
}
$words[0] now contains only letters which also occur in every other word and it only remains to split them into an array and sort the array.
#!/usr/bin/perl use v5.16; # The Weekly Challenge - 2023-06-05 use utf8; # Week 220 task 1 - Common characters use strict; # Peter Campbell Smith use warnings; # Blog: http://ccgi.campbellsmiths.force9.co.uk/challenge common_characters('Perl', 'Rust', 'Raku'); common_characters('mouse', 'house', 'esoteric', 'some', 'mesolithic', 'Thames', 'semibreve'); common_characters('ring', 'sing', 'ping', 'zing', 'shopping', 'single', 'mingle', 'gin'); sub common_characters { my (@words, $w, @letters); # delete from $word[0] any letters not in all the other words @words = @_; for $w (1 .. scalar @words - 1) { $words[0] =~ s|[^$words[$w]]||gi; } @letters = sort(split('', lc($words[0]))); # show results say qq[\nInput: \@words = ('] . join(qq[', '], @_) . q[')]; say qq[Output: ('] . join(qq[', '], @letters) . q[')]; }
Input: @words = ('Perl', 'Rust', 'Raku') Output: ('r') Input: @words = ('mouse', 'house', 'esoteric', 'some', 'mesolithic', 'Thames', 'semibreve') Output: ('e', 's') Input: @words = ('ring', 'sing', 'ping', 'zing', 'shopping', 'single', 'mingle', 'gin') Output: ('g', 'i', 'n')
Any content of this website which has been created by Peter Campbell Smith is in the public domain