Perl Weekly Challenge #221 - Good Strings, Bad Strings
Hi everybody! Very limited time this week so just a brief blog post.
This week we're looking for any words in the list that can be created only using letters from a dictionary string. Then print the number of characters in the good words.
Here's the code:
#!/usr/bin/perl
use strict;
use v5.24;
my %chars;
$chars{$_}++ for (split(//, shift));
my $total;
foreach (@ARGV) {
my @currWordChars = split(//, $_);
my %list = %chars;
my $notFound;
for my $char (@currWordChars) {
if ($list{$char}) {
$list{$char}--;
} else {
$notFound = 1;
last;
}
}
$total += ($notFound ? 0 : @currWordChars);
}
say $total;
So we try every single word against a hash of the dictionary letters, and if we're missing a letter we skip that word. We do this by making a copy of the dictionary hash and removing letters as we use them to create the word we're currently looking at.
A very simple solution and I started work on the second one but didn't have enough time available. Have a good week and I'll hopefully see you next week!
Leave a comment