DEV Community

oldtechaa
oldtechaa

Posted on • Edited on

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;
Enter fullscreen mode Exit fullscreen mode

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!

Image of Timescale

Timescale – the developer's data platform for modern apps, built on PostgreSQL

Timescale Cloud is PostgreSQL optimized for speed, scale, and performance. Over 3 million IoT, AI, crypto, and dev tool apps are powered by Timescale. Try it free today! No credit card required.

Try free

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more