Maximum triangle path sum: Difference between revisions
m
syntax highlighting fixup automation
(→{{header|Picat}}: Split into subsections) |
Thundergnat (talk | contribs) m (syntax highlighting fixup automation) |
||
Line 47:
{{trans|Python}}
<
L tri.len > 1
V t0 = tri.pop()
Line 73:
27 02 92 23 08 71 76 84 15 52 92 63 81 10 44 10 69 93’
print(solve(&data.split("\n").map(row -> row.split(‘ ’, group_delimiters' 1B).map(Int))))</
{{out}}
Line 81:
=={{header|Action!}}==
<
IF a>b THEN RETURN (a) FI
RETURN (b)
Line 130:
PrintI(data(0))
RETURN</
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Maximum_triangle_path_sum.png Screenshot from Atari 8-bit computer]
Line 138:
=={{header|Ada}}==
<
procedure Max_Sum is
Line 178:
end loop;
Put_Line(Integer'Image(Triangle(1)));
end Max_Sum;</
{{out}}
<pre> 1320
Line 186:
{{works with|ALGOL 68G|Any - tested with release 2.6.win32}}
Basically the same algorithm as Ada and C++ but using a triangular matrix.
<
[ 1]INT row 1 := ( 55 );
Line 232:
print( ( triangle[1][1], newline ) )
</syntaxhighlight>
{{out}}
<pre>
Line 240:
=={{header|AppleScript}}==
{{Trans|JavaScript}}
<
-- Working from the bottom of the triangle upwards,
Line 417:
return lst
end tell
end zipWith3</
{{Out}}
<pre>1320</pre>
=={{header|Astro}}==
<
let a = val t
for i in a.length-1..-1..1, c in linearindices a[r]:
Line 450:
@print maxpathsum test
</syntaxhighlight>
=={{header|AutoHotkey}}==
<syntaxhighlight lang="autohotkey"></syntaxhighlight>
Examples:<
(join ltrim
55,
Line 492:
}
MsgBox % data[1] "`n" path[1]</
Outputs:<pre>1320
55+94+95+77+97+7+48+72+76+83+64+90+48+80+84+85+94+71</pre>
=={{header|AWK}}==
<syntaxhighlight lang="awk">
# syntax: GAWK -f MAXIMUM_TRIANGLE_PATH_SUM.AWK filename(s)
{ printf("%s\n",$0)
Line 519:
}
function max(x,y) { return((x > y) ? x : y) }
</syntaxhighlight>
{{out}}
<pre>
Line 550:
=={{header|Bracmat}}==
<
55
94 48
Line 593:
| out$!Max
)
)</
{{out}}
<pre>1320</pre>
=={{header|C}}==
<syntaxhighlight lang="c">
#include <stdio.h>
#include <math.h>
Line 644:
return 0;
}
</syntaxhighlight>
{{out}}
<pre>
Line 652:
=={{header|C sharp|C#}}==
<
using System;
Line 702:
}
</syntaxhighlight>
{{out}}
<pre>Maximum total: 1320</pre>
Line 708:
=={{header|C++}}==
{{trans|Ada}}
<
/* Algorithm complexity: n*log(n) */
#include <iostream>
Line 747:
std::cout << "Maximum total: " << triangle[0] << "\n\n";
}
</syntaxhighlight>
{{out}}
<pre>Maximum total: 1320</pre>
Line 753:
=={{header|Clojure|ClojureScript}}==
<
(ns clojure.examples.rosetta
(:gen-class)
Line 808:
(println (max-sum nested-list))
</syntaxhighlight>
{{out}}
<pre>1320</pre>
=={{header|Common Lisp}}==
<
(let ((triangle (loop for line = (read-line s NIL NIL)
while line
Line 836:
(find-max-path-sum s)))
(format T "~a~%" (with-open-file (f "triangle.txt")
(find-max-path-sum f)))</
{{Out}}
Line 843:
=={{header|D}}==
<
import std.stdio, std.algorithm, std.range, std.file, std.conv;
Line 851:
.array)[0]
.writeln;
}</
{{out}}
<pre>1320</pre>
Line 858:
{{trans|C#}}
ELENA 5.0 :
<
import extensions;
import extensions'math;
Line 909:
console.printLine("Maximum total: ", list[0][0])
}</
{{out}}
<pre>
Line 916:
=={{header|Elixir}}==
<
def triangle_path(text) do
text
Line 958:
IO.puts Maximum.triangle_path(text)
</syntaxhighlight>
{{out}}
Line 967:
=={{header|Erlang}}==
Reads the data from the file "triangle.txt"
<syntaxhighlight lang="erlang">
-mode(compile).
-import(lists, [foldl/3]).
Line 993:
fold_rest([A], [B]) -> [A+B];
fold_rest([A1 | [A2|_] = As], [B|Bs]) -> [B + max(A1,A2) | fold_rest(As, Bs)].
</syntaxhighlight>
{{Out}}
<pre>
Line 1,000:
=={{header|ERRE}}==
<syntaxhighlight lang="erre">
PROGRAM TRIANGLE_PATH
Line 1,057:
PRINT(TRI[0])
END PROGRAM
</syntaxhighlight>
=={{header|Factor}}==
<
math.order math.parser math.vectors prettyprint sequences
splitting ;
Line 1,073:
reduce first ;
"triangle.txt" parse-triangle max-triangle-path-sum .</
{{out}}
<pre>
Line 1,080:
=={{header|Forth}}==
<
\ Triangle representation; words created by this defining word return the address of element
\ specified by its row number and position within that row, both indexed from 0.
Line 1,121:
;
MAX-SUM .</
{{out}}
<pre>
Line 1,134:
For input, free-format is convenient. Bad input still is a problem, and can lead to puzzles. If say when N values are to be read but an input line is short of numbers, then additional lines will be read and confusion is likely. So, read the file's record into a text variable and then extract the expected N values from that. Should a problem arise, then the troublesome record can be shown.
<syntaxhighlight lang="fortran">
MODULE PYRAMIDS !Produces a pyramid of numbers in 1-D array.
INTEGER MANY !The usual storage issues.
Line 1,245:
CALL REFINE !Only the result by more cunning.
END
</syntaxhighlight>
Output:
Line 1,333:
=={{header|FreeBASIC}}==
<
' compile with: fbc -s console
Line 1,393:
Print : Print "hit any key to end program"
Sleep
End</
{{out}}<pre> maximum triangle path sum = 1320</pre>
=={{header|Go}}==
<
import (
Line 1,451:
}
fmt.Println(d[0])
}</
{{Out}}
<pre>
Line 1,458:
=={{header|Haskell}}==
<
f x y z = x + max y z
g xs ys = zipWith3 f xs ys $ tail ys
solve = head . foldr1 g
main = readFile "triangle.txt" >>= print . solve . parse</
{{out}}
<pre>1320</pre>
Line 1,468:
Or, inlining the data for quick testing, and using an applicative expression:
<
maxPathSum :: [[Int]] -> Int
Line 1,499:
[06, 71, 28, 75, 94, 48, 37, 10, 23, 51, 06, 48, 53, 18, 74, 98, 15],
[27, 02, 92, 23, 08, 71, 76, 84, 15, 52, 92, 63, 81, 10, 44, 10, 69, 93]
]</
{{Out}}
<pre>1320</pre>
=={{header|J}}==
<
maxSum=: [: {. (+ (0 ,~ 2 >./\ ]))/ NB. find max triangle path sum</
'''Example Usage'''
<
1320</
Explanation:
Line 1,519:
Instead of padding, we could instead trim the other argument to match the current reduced row length.
<
However, this turns out to be a slightly slower approach, because we are doing a little more work for each row.
Line 1,527:
=={{header|Java}}==
{{works with|Java|8}}
<
import static java.util.Arrays.stream;
Line 1,545:
System.out.println(data[0][0]);
}
}</
<pre>1320</pre>
Line 1,552:
===ES5===
====Imperative====
<
var arr = [
[55],
Line 1,592:
console.log(arr);
</syntaxhighlight>
{{out}}
<
[ [ 1320 ] ]
</syntaxhighlight>
====Functional====
{{trans|Haskell}}
<
// Right fold using final element as initial accumulator
Line 1,650:
)[0];
})();</
{{out}}
<syntaxhighlight lang
===ES6===
====Imperative====
<
function distilLastLine() {
Line 1,697:
];
console.log(maximumTrianglePathSum(theTriangle));</
{{out}}
<syntaxhighlight lang
====Functional====
{{Trans|Haskell}}
<
"use strict";
Line 1,768:
[27, 2, 92, 23, 8, 71, 76, 84, 15, 52, 92, 63, 81, 10, 44, 10, 69, 93]
]);
})();</
{{Out}}
<pre>1320</pre>
Line 1,776:
the outer loop is implemented using <tt>reduce</tt>.
The input array is identical to that in the Javascript section and is therefore omitted here.<
def solve:
Line 1,787:
. as $in
| reduce range(length -2; -1; -1) as $i
($in[-1]; update( $in[$i] ) ) ;</
=={{header|Julia}}==
{{works with|Julia|0.6}}
<
function maxpathsum(t::Array{Array{I, 1}, 1}) where I
T = deepcopy(t)
Line 1,822:
[27, 02, 92, 23, 08, 71, 76, 84, 15, 52, 92, 63, 81, 10, 44, 10, 69, 93]]
@show maxpathsum(test)</
{{out}}
Line 1,829:
=={{header|Kotlin}}==
{{trans|C}}
<
val tri = intArrayOf(
Line 1,868:
println("Maximum total = ${triangle[0]}")
}
}</
{{out}}
Line 1,880:
While the solutions here are clever, I found most of them to be hard to follow. In fact, none of them are very good for showing how the algorithm works. So I wrote this Lua version for maximum readability.
<
{ 55 },
{ 94, 48 },
Line 1,932:
print(solve(triangleSmall))
print(solve(triangleLarge))
</syntaxhighlight>
{{out}}
Line 1,939:
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<
ClearAll[DoStep,MaximumTrianglePathSum]
DoStep[lst1_List,lst2_List]:=lst2+Join[{First[lst1]},Max/@Partition[lst1,2,1],{Last[lst1]}]
MaximumTrianglePathSum[triangle_List]:=Max[Fold[DoStep,First[triangle],Rest[triangle]]]</
{{out}}
<pre>MaximumTrianglePathSum[nums]
Line 1,949:
=={{header|Nim}}==
{{trans|Python}}
<
proc solve(tri: seq[seq[int]]): int =
Line 1,979:
echo solve data.splitLines.map((x: string) => x.strip.split.map parseInt)
</syntaxhighlight>
{{out}}
Line 1,985:
=={{header|PARI/GP}}==
<
forstep(i=#V,2,-1,V[i-1]+=vector(i-1,j,max(V[i][j],V[i][j+1]))); V[1][1]</
{{out}}
<pre>%1 = 1320</pre>
Line 1,992:
=={{header|Pascal}}==
testet with freepascal, should run under Turbo Pascal, therefore using static array and val, and Delphi too.
<
{'triangle.txt'
* one element per line
Line 2,097:
dec(h);
end;
end.</
{{out}}
<pre>height sum
Line 2,109:
=={{header|Perl}}==
<
use List::Util 'max';
Line 2,120:
}
say max(@sum);</
{{out}}
<pre>
Line 2,128:
=={{header|Phix}}==
<!--<
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #004080;">sequence</span> <span style="color: #000000;">tri</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{{</span><span style="color: #000000;">55</span><span style="color: #0000FF;">},</span>
Line 2,157:
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #0000FF;">?</span><span style="color: #000000;">tri</span><span style="color: #0000FF;">[</span><span style="color: #000000;">1</span><span style="color: #0000FF;">][</span><span style="color: #000000;">1</span><span style="color: #0000FF;">]</span>
<!--</
{{out}}
<pre>
Line 2,165:
=={{header|Picat}}==
===Mode directed tabling===
<
pp(Row,_Column,Tri,Sum),Row>Tri.length => Sum=0.
pp(Row,Column,Tri,Sum) ?=>
Line 2,172:
pp(Row,Column,Tri,Sum) =>
pp(Row+1,Column+1,Tri,Sum1),
Sum = Sum1+Tri[Row,Column].</
===Loop based approach===
<
if Sum > M.get(max_val,0) then
M.put(max_val,Sum)
Line 2,184:
pp2(Row,Column+I, Sum+Tri[Row,Column+I], Tri, M)
end
end.</
===Recursion===
{{trans|Prolog}}
<
data(N, T),
path(1, T, V).
Line 2,219:
[85, 32, 25, 85, 57, 48, 84, 35, 47, 62, 17, 1, 1, 99, 89, 52],
[6, 71, 28, 75, 94, 48, 37, 10, 23, 51, 6, 48, 53, 18, 74, 98, 15],
[27, 2, 92, 23, 8, 71, 76, 84, 15, 52, 92, 63, 81, 10, 44, 10, 69, 93]].</
===Test===
<
go =>
Line 2,264:
{06,71,28,75,94,48,37,10,23,51,06,48,53,18,74,98,15},
{27,02,92,23,08,71,76,84,15,52,92,63,81,10,44,10,69,93}
}.</
{{out}}
Line 2,278:
=={{header|PicoLisp}}==
{{trans|Common Lisp}}
<
(let (Lst (reverse Lst) R (car Lst))
(for I (cdr Lst)
Line 2,289:
R )
I ) ) )
(car R) ) )</
=={{header|PL/I}}==
{{trans|REXX}}
<
triang: Proc Options(Main);
Dcl nn(18,18) Bin Fixed(31);
Line 2,334:
get string(vla) Edit((nn(r,j) Do j=1 To r))(f(3));
End;
End;</
{{out}}
<pre>maximum path sum: 1320</pre>
=={{header|Prolog}}==
<
data(N, T),
path(0, T, V).
Line 2,380:
[27, 2, 92, 23, 8, 71, 76, 84, 15, 52, 92, 63, 81, 10, 44, 10, 69, 93]].
</syntaxhighlight>
{{out}}
<pre> ?- max_path(1, V).
Line 2,392:
=={{header|Python}}==
A simple mostly imperative solution:
<
while len(tri) > 1:
t0 = tri.pop()
Line 2,419:
27 02 92 23 08 71 76 84 15 52 92 63 81 10 44 10 69 93"""
print solve([map(int, row.split()) for row in data.splitlines()])</
{{out}}
<pre>1320</pre>
A more functional version, similar to the Haskell entry (same output):
<
f = lambda x, y, z: x + max(y, z)
g = lambda xs, ys: list(imap(f, ys, xs, xs[1:]))
data = [map(int, row.split()) for row in open("triangle.txt")][::-1]
print reduce(g, data)[0]</
And, updating a little for Python 3 (in which ''itertools'' no longer defines '''imap''', and '''reduce''' now has to be imported from ''functools''), while inlining the data for ease of testing:
Line 2,435:
{{Trans|JavaScript}}
{{Works with|Python|3|7}}
<
from functools import (reduce)
Line 2,476:
[27, 2, 92, 23, 8, 71, 76, 84, 15, 52, 92, 63, 81, 10, 44, 10, 69, 93]
])
)</
{{Out}}
<pre>1320</pre>
=={{header|Racket}}==
<
(require math/number-theory)
Line 2,539:
#(55 94 48 95 30 96 77 71 26 67))
(check-equal? (maximum-triangle-path-sum test-triangle) 321)
)</
{{out}}
<pre>1320</pre>
Line 2,547:
{{works with|Rakudo|2018.03}}
The <tt>Z+</tt> and <tt>Zmax</tt> are examples of the zipwith metaoperator. Note also we can use the <tt>Zmax</tt> metaoperator form because <tt>max</tt> is define as an infix in Perl 6.
<syntaxhighlight lang="raku"
94 48
95 30 96
Line 2,582:
# Or, instead of using reverse, one could also define the op as right-associative.
sub infix:<rop>(@a,@b) is assoc('right') { @a Z+ (@b Zmax @b[1..*]) }
put [rop] $triangle.lines.map: { [.words] }</
{{out}}
Line 2,592:
The method used is very efficient and performs very well for triangles that have thousands of rows (lines).
<br>For an expanded discussion of the program method's efficiency, see the discussion page.
<
@.=.; @.1 = 55
@.2 = 94 48
Line 2,623:
end /*r*/
/*stick a fork in it, we're all done. */
say 'maximum path sum: ' #.1.1 /*show the top (row 1) pyramid number. */</
'''output''' using the data within the REXX program:
<pre>
Line 2,630:
=={{header|Ring}}==
<
# Project : Maximum triangle path sum
Line 2,685:
see "maximum triangle path sum = " + matrix[1][1]
</syntaxhighlight>
Output:
<pre>
Line 2,692:
=={{header|Ruby}}==
<
" 55
94 48
Line 2,717:
x.zip(maxes).map{|a,b| a+b}
}.max
# => 1320</
=={{header|Rust}}==
{{works with|Rust|1.3}}
<
fn max_path(vector: &mut Vec<Vec<u32>>) -> u32 {
Line 2,769:
println!("{}", max_value);
//=> 7273
}</
=={{header|Scala}}==
<
// Solution:
def sum(triangle: Array[Array[Int]]) =
Line 2,792:
println(sum(parseLines(triangle)))
println(sum(parseFile("triangle.txt")))
}</
{{out}}
<pre>321
Line 2,801:
Iterative solution:
<
ARGF.each { |line|
Line 2,812:
}
say sum.max</
Recursive solution:
<
func max_value(i=0, j=0) is cached {
Line 2,822:
}
say max_value()</
{{out}}
<pre>% sidef maxpath.sf triangle.txt
Line 2,828:
=={{header|Stata}}==
<
mata
a = st_data(.,.)
Line 2,838:
}
a[1,1]
end</
'''Output'''
Line 2,846:
=={{header|Tcl}}==
{{works with|Tcl|8.6}}
<
proc maxTrianglePathSum {definition} {
Line 2,890:
27 02 92 23 08 71 76 84 15 52 92 63 81 10 44 10 69 93
}]
# Reading from a file is left as an exercise…</
{{out}}
<pre>
Line 2,897:
=={{header|VBScript}}==
<syntaxhighlight lang="vb">
'Solution derived from http://stackoverflow.com/questions/8002252/euler-project-18-approach.
Line 2,923:
objinfile.Close
Set objfso = Nothing
</syntaxhighlight>
{{In}}
Line 2,953:
=={{header|Wren}}==
{{trans|Go}}
<
" 55",
" 94 48",
Line 2,986:
}
}
System.print(d[0])</
{{out}}
Line 2,996:
{{trans|Python}}
The two Python solutions:
<
while(tri.len()>1){
t0:=tri.pop();
Line 3,003:
'wrap([(i,t)]){ t + t0[i].max(t0[i+1]) }]])
}
tri[0][0].println();</
<
fcn f(x,y,z){ x + y.max(z) }
fcn g(xs,ys){ Utils.zipWith(f,ys,xs,xs[1,*]); }
data.reverse().reduce(g)[0].println();</
{{trans|Go}}
<
d:=lines[-1].copy();
foreach row in ([lines.len()-2..0,-1]){
Line 3,019:
}
}
println(d[0]);</
{{out}}
<pre>
|