diff options
| -rwxr-xr-x | challenge-151/2colours/raku/ch-1.raku | 17 | ||||
| -rwxr-xr-x | challenge-151/2colours/raku/ch-2.raku | 21 |
2 files changed, 38 insertions, 0 deletions
diff --git a/challenge-151/2colours/raku/ch-1.raku b/challenge-151/2colours/raku/ch-1.raku new file mode 100755 index 0000000000..c572d39c71 --- /dev/null +++ b/challenge-151/2colours/raku/ch-1.raku @@ -0,0 +1,17 @@ +#!/usr/bin/env raku + +multi minimum-depth(@tree where *.first == 0 --> 0) {} +multi minimum-depth(@tree where * == 1 --> 1) {} +multi minimum-depth(@tree) { minimum-depth(@tree.skip.List, 1, (True,)) } +multi minimum-depth((), $current-assumption, @) { $current-assumption } +multi minimum-depth((@head, *@tail), $current-assumption, @prev-filter) { + my @common-children = @head.rotor(2, :partial); + when +@common-children <= (-1 R// @prev-filter.first: *.so, :end, :k) { $current-assumption } + when @prev-filter Z&& @common-children + andthen .grep: * !=== False + andthen .map: *.all eq '*' + andthen .any { $current-assumption } + minimum-depth(@tail, $current-assumption + 1, @head.map(* ne '*').List); +} +my @tree-lines = prompt('Input: ').split('|').map(*.words.List); +say "Output: {minimum-depth(@tree-lines)}"; diff --git a/challenge-151/2colours/raku/ch-2.raku b/challenge-151/2colours/raku/ch-2.raku new file mode 100755 index 0000000000..d43a80019f --- /dev/null +++ b/challenge-151/2colours/raku/ch-2.raku @@ -0,0 +1,21 @@ +#!/usr/bin/env raku + +use experimental :cached; + +#`{ This looks very elegant but unfortunately, cached is broken with multiple dispatch and therefore the calls grow exponentially +multi max-sum(($x1, $x2, *@tl)) { max(max-sum(($x2, |@tl)), $x1 + max-sum(@tl)) } +multi max-sum(($x,)) {$x} +multi max-sum(() --> 0) {} +} + +sub max-sum(@list) is cached { + given @list { + when 0 { 0 } + when 1 { @list.first } + default { max max-sum(@list.skip), @list.first + max-sum(@list.skip: 2) } + } +} + +say max-sum((1,3,2,4,4,1,9,1)); #16 +say max-sum((2, 4, 5)); #7 +say max-sum((4, 2, 3, 6, 5, 3)); #13 |
