aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorSimon Proctor <simon.proctor@zoopla.co.uk>2020-04-20 10:55:25 +0100
committerSimon Proctor <simon.proctor@zoopla.co.uk>2020-04-20 10:55:25 +0100
commitd12a3a1c898753060ececb57a4e6f2a10bed55db (patch)
treef71a6ad6bea1cee9ccffb9ffb78a06a730b8a979
parent657c679062554b37200911f2abf7bb44ccdb3a42 (diff)
downloadperlweeklychallenge-club-d12a3a1c898753060ececb57a4e6f2a10bed55db.tar.gz
perlweeklychallenge-club-d12a3a1c898753060ececb57a4e6f2a10bed55db.tar.bz2
perlweeklychallenge-club-d12a3a1c898753060ececb57a4e6f2a10bed55db.zip
Prefixes
-rw-r--r--challenge-057/simon-proctor/raku/ch-2.p644
1 files changed, 44 insertions, 0 deletions
diff --git a/challenge-057/simon-proctor/raku/ch-2.p6 b/challenge-057/simon-proctor/raku/ch-2.p6
new file mode 100644
index 0000000000..f52bd713b4
--- /dev/null
+++ b/challenge-057/simon-proctor/raku/ch-2.p6
@@ -0,0 +1,44 @@
+#!/usr/bin/env raku
+
+use v6;
+
+#| Given a list of strings print the list of shortest unique prefixes
+sub MAIN (
+ *@words where *.elems >= 2
+) {
+ my @word-arrays = @words.map( *.comb );
+ my %result = prefix-hash( @word-arrays );
+ .say for traverse( %result );
+
+}
+
+sub traverse ( %hash ) {
+ my @out;
+
+ for %hash.keys -> $key {
+ if ( %hash{$key} ~~ Hash ) {
+ my @res = traverse( %hash{$key} );
+ @out.push( [ $key, |$_] ) for @res;
+ } else {
+ @out.push( [ $key, ] );
+ }
+ }
+
+ return @out.map( *.join("") );
+}
+
+sub prefix-hash( @arrays ) {
+ my %hash;
+
+ for @arrays -> [$key, *@rest] {
+ %hash{$key} //= [];
+ %hash{$key}.push( @rest );
+ }
+
+ for %hash.keys -> $key {
+ if %hash{$key}.elems > 1 {
+ %hash{$key} = prefix-hash( %hash{$key} );
+ }
+ }
+ return %hash;
+}