From 0ed9c0fa187e3320ac6b64bee748be1986609d07 Mon Sep 17 00:00:00 2001 From: Mohammad S Anwar Date: Mon, 20 Apr 2020 16:36:07 +0100 Subject: - Added solution by Pete Houston. --- challenge-057/pete-houston/perl/5702.pm | 43 +++++++++++++++++++++++++++++++++ challenge-057/pete-houston/perl/ch-2.pl | 11 +++++++++ 2 files changed, 54 insertions(+) create mode 100644 challenge-057/pete-houston/perl/5702.pm create mode 100644 challenge-057/pete-houston/perl/ch-2.pl (limited to 'challenge-057') 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; -- cgit