Perl Weekly Challenge #216 - Choosing a Nickname for Your Car

Hi everybody!

Just one solution to the first task in the weekly challenge this week, and it's a different type. I didn't have time to do any more, and this solution might not be the most efficient or cleanest, but it looks reasonably good to me.

The goal is to find any words which contain all the letters of the car registration number. I assume this would be to find a nickname for your car based on its registration number. In the examples, all of the words are lower-case, so I just assume that my inputs are lower-case. This week I used a few language features that I haven't used in previous challenges, like loop labels, POSIX classes, and a variable regex. As usual, the first argument to the script (without the space in the rego in the examples) is the registration and the rest of the arguments are the words to match it to.

Here's the code: #!/usr/bin/perl

use strict;
use warnings;
use v5.24;

my %reg;
foreach (split(//, shift)) {
    my ($char) = ($_ =~ /([[:alpha:]])/);
    $reg{lc($char)}++ if $char;
}

WORD:
foreach (@ARGV) {
    my $word = $_;
    MATCH:
    foreach (keys %reg) {
        my $char = $_;
        my $count = $reg{$_};

        next WORD if $word !~ /${char}{$count,}/;
    }
    say $word;
}

Even though none of the examples include registrations with duplicate letters, to protect against this we create a hash containing the letters in the registration number as keys and the number of occurrences as values. Then we search each word for the characters in the hash and make sure that we have at least as many occurrences as the hash value. If we've successfully run through all the values in the hash we say the word that successfully matched.

That's all for this week, like I said I ran out of time, so hopefully I'll see you next week!

Leave a comment

About oldtechaa

user-pic Just getting back into Perl programming. I have a personal project, SeekMIDI, a small graphical MIDI sequencer.