Last active
May 9, 2019 08:38
-
-
Save gugod/690ba68fafb3c987a6d37a77d5ebe49f to your computer and use it in GitHub Desktop.
perl-weekly-challenge-007
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use v5.28; | |
sub sum { | |
my $s = 0; | |
$s += $_ for @_; | |
return $s; | |
} | |
sub digits { | |
return split //, $_[0]; | |
} | |
sub is_niven { | |
my ($n) = @_; | |
return $n % sum(digits($n)) == 0; | |
} | |
say for grep { is_niven($_) } 1...50; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use v5.28; | |
use feature qw(signatures); | |
no warnings qw(experimental::signatures); | |
sub find_shortest_ladder($word1, $word2, $wordlist) { | |
return () unless length($word1) == length($word2); | |
my @letters = ('a'...'z'); | |
my %dict = map { $_ => 1 } grep { length($_) == length($word1) } @$wordlist; | |
return () unless ($dict{$word1} && $dict{$word2}); | |
my %trace = ( $word1 => undef ); | |
my @queue = ($word1); | |
my $found = 0; | |
while (!$found && @queue) { | |
my $w = shift @queue; | |
if ($w eq $word2) { | |
$found = 1; | |
last; | |
} else { | |
for my $i ( 0 ... length($w)-1 ) { | |
for my $letter ( @letters ) { | |
my $w2 = $w; | |
substr($w2, $i, 1) = $letter; | |
if ($dict{$w2} && !exists($trace{$w2})) { | |
$trace{$w2} = $w; | |
push @queue, $w2; | |
} | |
} | |
} | |
} | |
} | |
my @ladder = (my $w = $word2); | |
while ($trace{$w}) { | |
push @ladder, $trace{$w}; | |
$w = $trace{$w}; | |
} | |
return reverse @ladder; | |
} | |
my @wordlist = do { | |
open my $fh, '<', '/usr/share/dict/words'; | |
grep { /^[a-z]+$/ } map { chomp($_); $_ } <$fh>; | |
}; | |
my @ladder = find_shortest_ladder("cold", "warm", \@wordlist); | |
say join ", ", @ladder; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment