Skip to content

Instantly share code, notes, and snippets.

@filipevarjao
Last active November 20, 2016 13:49
Show Gist options
  • Select an option

  • Save filipevarjao/1a1bcd4a9d1a573d3a816c0cce728069 to your computer and use it in GitHub Desktop.

Select an option

Save filipevarjao/1a1bcd4a9d1a573d3a816c0cce728069 to your computer and use it in GitHub Desktop.
Pairwise disjoint intervals
-module(solution).
-export([start/2]).
-spec start([any()],[any()]) -> 'ok'.
start(A, B) ->
interval(A, B, []).
-spec interval([any()],[any()],[[any(),...]]) -> 'ok'.
interval([], [], Intv) ->
[[_|_]|Tail] = Intv,
pairwise(Intv, Tail, [], []);
interval([HeadA|TailA], [HeadB|TailB], Intv) ->
interval(TailA, TailB, Intv ++ [[HeadA,HeadB]]).
-spec pairwise([[any(),...],...],[[any(),...]],[[any(),...]],[[any(),...]]) -> 'ok'.
pairwise([[Inf|Sup]|Tail], [], Union, Overlap) ->
case Tail of
[] ->
io:write(length(Union));
_ ->
[[_|_]|SubTail] = Tail,
[Elem|_] = Sup,
case lists:member([Inf,Elem], Overlap) of
true ->
pairwise(Tail, SubTail, Union , Overlap);
false ->
pairwise(Tail, SubTail, Union ++ [[Inf, Elem]], Overlap)
end
end;
pairwise([[Inf|Sup]|Tail], [[H|T]|NextTail], Union, Overlap) when Inf >= H , Sup >= T ->
[Elem|_] = T,
case Inf =< Elem of
true ->
[NewSup|_] = Sup,
pairwise([[Inf|Sup]|Tail], NextTail, Union ++ [[H, NewSup]], Overlap ++ [[Inf,NewSup],[H,Elem]]);
false ->
pairwise([[Inf|Sup]|Tail], NextTail, Union, Overlap)
end;
pairwise([[Inf|Sup]|Tail], [[H|T]|NextTail], Union, Overlap) when Sup =< T , Inf =< H ->
[Elem|_] = Sup,
case Elem >= H of
true ->
[NewT|_] = T,
pairwise([[Inf|Sup]|Tail], NextTail, Union ++ [[Inf, NewT]], Overlap ++ [[Inf,Elem],[H,NewT]]);
false ->
pairwise([[Inf|Sup]|Tail], NextTail, Union, Overlap)
end.
% A = [1, 12, 42, 70, 36, -4, 43, 15]
% B = [5, 15, 44, 72, 36, 2, 69, 24 ]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment