Skip to content

Instantly share code, notes, and snippets.

@nchelluri
Created June 13, 2017 14:59
Show Gist options
  • Save nchelluri/39af3b434ed8d9647e853a1f7cd97c05 to your computer and use it in GitHub Desktop.
Save nchelluri/39af3b434ed8d9647e853a1f7cd97c05 to your computer and use it in GitHub Desktop.
Finds all words that can be made with a given string of letters
#!/usr/bin/env perl
use Modern::Perl '2015';
use autodie;
use experimental 'signatures';
use List::MoreUtils qw(uniq);
unless (@ARGV == 1) {
say "usage: $0 letters";
exit 1;
}
sub shuffle(@letters) {
if (@letters == 1) {
return @letters;
}
my @shuffled;
for (my $i = 0; $i < @letters; $i++) {
my @other_letters = @letters;
splice @other_letters, $i, 1;
my @other_letters_shuffled = shuffle(@other_letters);
for (my $j = 0; $j < @letters; $j++) {
push @shuffled, map { $letters[$i] . substr($_, 0, $j) } @other_letters_shuffled;
}
}
return uniq @shuffled;
}
my @shuffled = shuffle(split(//, $ARGV[0]));
open my $wordlist, '<', '/usr/share/dict/words';
chomp(my @words = <$wordlist>);
close $wordlist;
my %words = map { $_ => 1 } @words;
for my $candidate (@shuffled) {
if (exists($words{$candidate})) {
say $candidate;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment