Erlang Tape Equilibrium
-module(tape_equilibrium).
-export([tape_equilibrium/1]).
%% Faithful port of the PHP source: it accumulates the loop index i into
%% firstPart/secondPart rather than a[i], so this mirrors that behaviour
%% (including the quirk) rather than the classic tape-equilibrium formula.
tape_equilibrium(A) ->
N = length(A),
Total = lists:sum(A),
{_, _, Min} = lists:foldl(fun(I, {First, Second, MinV}) ->
First1 = First + I,
Second1 = Second - I,
Diff = abs(First1 - Second1),
{First1, Second1, min(MinV, Diff)}
end, {0, Total, 1 bsl 128}, lists:seq(0, N - 2)),
Min.
This keeps left and right running sums and updates the smallest difference at each split point.
Erlang Triangle
-module(triangle).
-export([triangle/1]).
triangle(A) ->
Sorted = lists:sort(A),
N = length(Sorted),
case N < 3 of
true -> 0;
false ->
Triples = lists:zip3(Sorted, tl(Sorted), tl(tl(Sorted))),
case lists:any(fun({X, Y, Z}) -> X > 0 andalso X > (Z - Y) end, Triples) of
true -> 1;
false -> 0
end
end.
This sorts the values and checks nearby triples, because a valid triangle only needs one local match after sorting.