diff options
| -rwxr-xr-x | challenge-113/feng-chang/raku/ch-1.raku | 11 | ||||
| -rwxr-xr-x | challenge-113/feng-chang/raku/ch-2.raku | 68 |
2 files changed, 79 insertions, 0 deletions
diff --git a/challenge-113/feng-chang/raku/ch-1.raku b/challenge-113/feng-chang/raku/ch-1.raku new file mode 100755 index 0000000000..3b3e4cb4b1 --- /dev/null +++ b/challenge-113/feng-chang/raku/ch-1.raku @@ -0,0 +1,11 @@ +#!/bin/env raku + +subset Digit of UInt where * ≤ 9; + +sub MAIN(UInt:D $N = 25, Digit:D $D = 7) { + put do given $N { + when $N ~~ /$D/ { 1 } + when $N == (1..^$N).grep(/$D/).combinations».sum.any { 1 } + default { 0 } + } +} diff --git a/challenge-113/feng-chang/raku/ch-2.raku b/challenge-113/feng-chang/raku/ch-2.raku new file mode 100755 index 0000000000..0a25d20ea9 --- /dev/null +++ b/challenge-113/feng-chang/raku/ch-2.raku @@ -0,0 +1,68 @@ +#!/bin/env raku + +grammar Tree { + rule TOP { '(' <node> <TOP> ** 0..2 ')' } + token node { \d+ } +} + +class TreeActions { + method TOP($/) { + my %h = root => $<node>.made; + %h<left> = $<TOP>[0].made if $<TOP>[0]; + %h<right> = $<TOP>[1].made if $<TOP>[1]; + + make %h; + } + + method node($/) { make $/.Int } +} + +multi MAIN('test') { + use Test; + + is-deeply Tree.parse('(111)', :actions(TreeActions)).made, { root => 111 }, '(111) parsed'; + is-deeply + Tree.parse('(6 (2) (3))', :actions(TreeActions)).made, + { root => 6, left => { root => 2 }, right => { root => 3 } }, + '(6 (2) (3)) parsed'; + + done-testing; +} + +sub tree-sum($t --> Int:D) { + $t ?? $t<root> + tree-sum($t<left>) + tree-sum($t<right>) !! 0 +} + +sub modify-tree($t, Int:D $sum) { + return unless $t; + + $t<root> = $sum - $t<root>; + modify-tree($t<left>, $sum); + modify-tree($t<right>, $sum); +} + +sub print-tree(Hash:D $t) { + print '(', $t<root>; + + if $t<left>.defined { + print ' '; + print-tree($t<left>); + } + + if $t<right>.defined { + print ' '; + print-tree($t<right>); + } + + print ')'; +} + +multi MAIN(Str:D $t = '(1(2(4(7)))(3(5)(6)))') { + my Hash $tree .= new(Tree.parse($t, :actions(TreeActions)).made); + + my $sum = tree-sum($tree); + modify-tree($tree, $sum); + + print-tree($tree); + put ''; +} |
