-
Notifications
You must be signed in to change notification settings - Fork 11
/
fibsum.raku
executable file
·48 lines (39 loc) · 1.08 KB
/
fibsum.raku
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
#!/usr/bin/env raku
#
# fibsum.raku -- display all solutions of fibsum($N)
#
# LICENSE: CC0
# To the extent possible under law, Kang-min Liu has waived all
# copyright and related or neighboring rights to fibsum.raku.
# This work is published from: Taiwan.
my @fib = 1, 2, { $^a + $^b } ... *;
sub fibsum(Int $n) {
my @subfib = @fib[0 ... @fib.first({ $^fib > $n }, :k)-1];
say " ... subfib = " ~ @subfib;
return sumsearch($n, @subfib);
}
sub sumsearch (Int $n, @nums) {
my @solutions = [];
if $n == 0 {
@solutions.push([]);
return @solutions;
}
if @nums.elems == 0 || $n < 0 {
return @solutions;
}
my $firstNum = @nums.pop();
my @s1 = sumsearch($n, @nums);
my @s2 = sumsearch($n - $firstNum, @nums).map({ $_.prepend($firstNum) });
@nums.push($firstNum);
@solutions.append(@s1);
@solutions.append(@s2);
return @solutions;
}
sub MAIN(Int $n) {
my @solutions = fibsum($n);
say "|fibsum($n)| = " ~ @solutions.elems;
say "\n$n";
for @solutions -> $s {
say " = " ~ @$s.join(" + ");
}
}