Maximum triangle path sum: Difference between revisions
Content added Content deleted
(→{{header|Perl 6}}: supply right-associative solution) |
(→{{header|Perl 6}}: eschew .rotate in favor of [1..*] slice) |
||
Line 57: | Line 57: | ||
<pre>1320</pre> |
<pre>1320</pre> |
||
⚫ | |||
=={{header|Perl 6}}== |
|||
⚫ | |||
<lang perl6>my @rows = slurp("triangle.txt").lines.map: { [.words] } |
<lang perl6>my @rows = slurp("triangle.txt").lines.map: { [.words] } |
||
while @rows > 1 { |
while @rows > 1 { |
||
my @last := @rows.pop; |
my @last := @rows.pop; |
||
@rows[*-1] = @rows[*-1] Z+ (@last Zmax @last. |
@rows[*-1] = @rows[*-1] Z+ (@last Zmax @last[1..*]); |
||
} |
} |
||
Line 70: | Line 69: | ||
<pre>1320</pre> |
<pre>1320</pre> |
||
Here's a more FPish version with the same output. We define our own operator and the use it in the reduction metaoperator form, <tt>[op]</tt>, which turns any infix into a list operator. |
Here's a more FPish version with the same output. We define our own operator and the use it in the reduction metaoperator form, <tt>[op]</tt>, which turns any infix into a list operator. |
||
<lang perl6>sub infix:<op>(@a,@b) { (@a Zmax @a. |
<lang perl6>sub infix:<op>(@a,@b) { (@a Zmax @a[1..*]) Z+ @b } |
||
say [op] slurp("triangle.txt").lines.reverse.map: { [.words] }</lang> |
say [op] slurp("triangle.txt").lines.reverse.map: { [.words] }</lang> |
||
Instead of using reverse, one could also define the op as right-associative. |
Instead of using reverse, one could also define the op as right-associative. |
||
<lang perl6>sub infix:<op>(@a,@b) is assoc('right') { @a Z+ (@b Zmax @b. |
<lang perl6>sub infix:<op>(@a,@b) is assoc('right') { @a Z+ (@b Zmax @b[1..*]) } |
||
say [op] slurp("triangle.txt").lines.map: { [.words] }</lang> |
say [op] slurp("triangle.txt").lines.map: { [.words] }</lang> |