Maximum triangle path sum: Difference between revisions

→‎{{header|Perl 6}}: eschew .rotate in favor of [1..*] slice
(→‎{{header|Perl 6}}: supply right-associative solution)
(→‎{{header|Perl 6}}: eschew .rotate in favor of [1..*] slice)
Line 57:
<pre>1320</pre>
 
Yes, theThe <tt>ZmaxZ+</tt> produces an extra wraparound value, but theand <tt>Z+Zmax</tt> throwsare itexamples away, since a zip operator will trim toof the shorterzipwith listmetaoperator. 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] }
 
while @rows > 1 {
my @last := @rows.pop;
@rows[*-1] = @rows[*-1] Z+ (@last Zmax @last[1.rotate.*]);
}
 
Line 70 ⟶ 69:
<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.
<lang perl6>sub infix:<op>(@a,@b) { (@a Zmax @a[1.rotate.*]) Z+ @b }
 
say [op] slurp("triangle.txt").lines.reverse.map: { [.words] }</lang>
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[1.rotate.*]) }
 
say [op] slurp("triangle.txt").lines.map: { [.words] }</lang>
Anonymous user