aboutsummaryrefslogtreecommitdiff
path: root/challenge-057
diff options
context:
space:
mode:
authorMohammad S Anwar <mohammad.anwar@yahoo.com>2020-04-20 16:36:07 +0100
committerMohammad S Anwar <mohammad.anwar@yahoo.com>2020-04-20 16:36:07 +0100
commit0ed9c0fa187e3320ac6b64bee748be1986609d07 (patch)
tree8cd209b9a1038c3750f1ed2232176fd54429b210 /challenge-057
parent599ec05e6782be84b424b933675948fd4572ce0a (diff)
downloadperlweeklychallenge-club-0ed9c0fa187e3320ac6b64bee748be1986609d07.tar.gz
perlweeklychallenge-club-0ed9c0fa187e3320ac6b64bee748be1986609d07.tar.bz2
perlweeklychallenge-club-0ed9c0fa187e3320ac6b64bee748be1986609d07.zip
- Added solution by Pete Houston.
Diffstat (limited to 'challenge-057')
-rw-r--r--challenge-057/pete-houston/perl/5702.pm43
-rw-r--r--challenge-057/pete-houston/perl/ch-2.pl11
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;