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>


The <tt>Z+</tt> and <tt>Zmax</tt> are examples of the zipwith metaoperator. We ought to be able to use <tt>[Z+]=</tt> as an assignment operator here, but rakudo has a bug. Note also we can use the <tt>Zmax</tt> metaoperator form because <tt>max</tt> is define as an infix in Perl 6.
=={{header|Perl 6}}==
Yes, the <tt>Zmax</tt> produces an extra wraparound value, but the <tt>Z+</tt> throws it away, since a zip operator will trim to the shorter list. We ought to be able to use <tt>[Z+]=</tt> as an assignment operator here, but rakudo has a bug. Note also we can use the <tt>Zmax</tt> metaoperator form because <tt>max</tt> is define as an infix in 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.rotate);
@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.rotate) Z+ @b }
<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.rotate) }
<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>