Maximum triangle path sum: Difference between revisions

Erlang version
(Added solution for Action!)
(Erlang version)
Line 963:
<pre>
1320
</pre>
 
=={{header|Erlang}}==
Reads the data from the file "triangle.txt"
<lang Erlang>
-mode(compile).
-import(lists, [foldl/3]).
 
main(_) ->
{ok, Tmat} = file:open("triangle.txt", [read, raw, {read_ahead, 16384}]),
Max = max_sum(Tmat, []),
io:format("The maximum total is ~b~n", [Max]).
 
max_sum(FD, Last) ->
case file:read_line(FD) of
eof -> foldl(fun erlang:max/2, 0, Last);
{ok, Line} ->
Current = [binary_to_integer(B) || B <- re:split(Line, "[ \n]"), byte_size(B) > 0],
max_sum(FD, fold_row(Last, Current))
end.
 
fold_row([], L) -> L;
fold_row([A|_] = Last, [B|_] = Current) ->
[A+B | fold_rest(Last, tl(Current))].
 
fold_rest([A], [B]) -> [A+B];
fold_rest([A1,A2|_] = Prev, [B|Bs]) -> [B + max(A1,A2) | fold_rest(tl(Prev), Bs)].
</lang>
{{Out}}
<pre>
The maximum total is 1320
</pre>
 
357

edits