diff options
Diffstat (limited to 'challenge-057')
| -rw-r--r-- | challenge-057/pete-houston/perl/5702.pm | 43 | ||||
| -rw-r--r-- | challenge-057/pete-houston/perl/ch-2.pl | 11 |
2 files changed, 54 insertions, 0 deletions
diff --git a/challenge-057/pete-houston/perl/5702.pm b/challenge-057/pete-houston/perl/5702.pm new file mode 100644 index 0000000000..3985383f6a --- /dev/null +++ b/challenge-057/pete-houston/perl/5702.pm @@ -0,0 +1,43 @@ +#!/usr/bin/env perl +use strict; +use warnings; + +main () unless caller; + +sub shortest_prefs { + my $wordlist = shift; + my $prefcounts = prefcounts (@$wordlist); + return [ map { minpref ($_, $prefcounts) } @$wordlist ]; +} + +sub prefcounts { + my @wordlist = @_; + my %counts; + for my $word (@wordlist) { + while (length ($word)) { + $counts{$word}++; + $word =~ s/.$//; + } + } + return \%counts; +} + +sub minpref { + my ($word, $counts) = @_; + for my $i (1 .. length ($word)) { + my $pref = substr $word, 0, $i; + return $pref if $counts->{$pref} == 1; + } + return ''; # If non-unique +} + +sub aref_from_argv { + # Sanitise input format + my @in = map { s/[",]//g; $_ } grep { ! /^[[\]]$/ } @ARGV; + return \@in; +} + +sub main { + my $out = shortest_prefs (aref_from_argv ()); + print '[ ', join (', ', map { qq{"$_"} } @$out), " ]\n"; +}
\ No newline at end of file diff --git a/challenge-057/pete-houston/perl/ch-2.pl b/challenge-057/pete-houston/perl/ch-2.pl new file mode 100644 index 0000000000..3d0aa24ea6 --- /dev/null +++ b/challenge-057/pete-houston/perl/ch-2.pl @@ -0,0 +1,11 @@ +use strict; +use warnings; + +use Test::More tests => 1; +use lib '.'; +require '5702.pm'; + +my $in = [ "alphabet", "book", "carpet", "cadmium", "cadeau", "alpine" ]; +my $want = [ "alph", "b", "car", "cadm", "cade", "alpi" ]; + +is_deeply shortest_prefs ($in), $want; |
