Skip to content

Instantly share code, notes, and snippets.

@7-fl
Created March 6, 2017 16:02
Show Gist options
  • Save 7-fl/4f1feca8aea29bff9b6a75b6035946f0 to your computer and use it in GitHub Desktop.
Save 7-fl/4f1feca8aea29bff9b6a75b6035946f0 to your computer and use it in GitHub Desktop.
-module(runs).
-compile(export_all).
-include_lib("eunit/include/eunit.hrl").
% [1, 4, 7, 2, 3]
% [1, 2, 3, 4, 7]
%
% What about [2, 3, 3, 4]??? => Done!
%
%---------------
runs_test() ->
%[] = process([]),
[{1,1}] = runs([1]),
[{1,3}] = runs([1,2,3]),
[{1,3}] = runs([1,2,2,3]),
[{1,3}, {5,5}] = runs([1,2,3, 5]),
[{1,4}, {7,9}] = runs([1,2,3,4, 7,8,9]),
[{1,4}, {7,7}, {9,10}] = runs([1,2,3,4, 7, 9,10]),
[{1,3}, {5,7}, {9,10}] = runs([1,2,3,3, 5,6,6,7, 9,9,10]),
[{1,10}] = runs([1,2,3,3,4,5,6,6,7,8,9,9,10]),
all_tests_passed.
runs(L) ->
L2 = w2:mysort(L),
L3 = nub(L2), %Remove duplicate line numbers: [1,2,3,3,4] => [1,2,3,4]
runs(L3, [], none, []).
runs([], Pairs, _NextNum, Run) -> %Base case: no more line numbers in first arg.
Pair = {last(Run), first(Run)}, %Create a pair from whatever was left in Run.
reverse([Pair|Pairs]); %Add final Pair to the other Pairs.
runs([X|Xs], Pairs, _NextNum, []) -> %Run is starting because Run =:= [].
runs(Xs, Pairs, X+1, [X]);
runs([X|Xs], Pairs, X, Run) -> %Run continues because NextNum =:= X.
runs(Xs, Pairs, X+1, [X|Run]);
runs([X|Xs], Pairs, _NextNum, Run) -> %Run has ended because NextNum =/= X.
Pair = {last(Run), first(Run)},
runs(Xs, [Pair|Pairs], X+1, [X]).
%--------------
first_test() ->
%first([]) => Crash!
1 = first([1, 2, 3, 4]),
all_tests_passed.
first([X|_]) ->
X.
%----------
last_test() ->
%last([]) => Crash!
4 = last([1, 2, 3, 4]),
all_tests_passed.
last(L) ->
first(reverse(L)).
%-------------
reverse_test() ->
[] = reverse([]),
[2, 1] = reverse([1, 2]),
[1, 2, 3] = reverse([3, 2, 1]),
all_tests_passed.
reverse(L) -> reverse(L, []).
reverse([], Acc) ->
Acc;
reverse([X|Xs], Acc) ->
reverse(Xs, [X|Acc]).
%-------------
contains_test() ->
false = contains(3, []),
false = contains(3, [1, 2]),
true = contains(3, [1, 2, 3]),
true = contains(3, [3, 1, 0]),
all_tests_passed.
contains(_, []) ->
false;
contains(N, [N|_]) ->
true;
contains(N, [_|Xs]) ->
contains(N, Xs).
%----------
nub_test() ->
[] = nub([]),
[a] = nub([a, a, a]),
[-1, 0, 1] = nub([-1, 0, -1, 0, 1, 1]),
[1, 2] = nub([1, 1, 2, 2, 1, 2, 1, 2]),
all_tests_passed.
nub(L) -> nub(L, []).
nub([], Acc) ->
reverse(Acc);
nub([X|Xs], Acc) ->
case contains(X, Acc) of
true -> nub(Xs, Acc);
false -> nub(Xs, [X|Acc])
end.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment