Skip to content

Instantly share code, notes, and snippets.

@egobrain
Created September 2, 2014 08:50
Show Gist options
  • Save egobrain/92034ad7b26640721f80 to your computer and use it in GitHub Desktop.
Save egobrain/92034ad7b26640721f80 to your computer and use it in GitHub Desktop.
-module(dups).
-export([
duplicates/1,
same_order_duplicates/1
]).
duplicates([]) -> {[], []};
duplicates(List) ->
[H|T] = lists:sort(List),
duplicates_(H, T, [], [H]).
duplicates_(_, [], DupAcc, Acc) ->
{DupAcc, Acc};
duplicates_(H, [H|T], [H|_]=DupAcc, Acc) ->
duplicates_(H, T, DupAcc, Acc);
duplicates_(H, [H|T], DupAcc, Acc) ->
duplicates_(H, T, [H|DupAcc], Acc);
duplicates_(_, [H|T], DupAcc, Acc) ->
duplicates_(H, T, DupAcc, [H|Acc]).
same_order_duplicates([]) -> {[], []};
same_order_duplicates(List) ->
List2 = lists:zip(List, lists:seq(1, length(List))),
[{H,_}=H0|T] = lists:sort(List2),
same_order_duplicates_(H, T, [], [H0]).
same_order_duplicates_(_, [], DupAcc, Acc) ->
Acc2 = lists:sort(fun({_, A}, {_, B}) -> A<B end, Acc),
Acc3 = [V||{V, _} <- Acc2],
{DupAcc, Acc3};
same_order_duplicates_(H, [{H,_}|T], [H|_]=DupAcc, Acc) ->
same_order_duplicates_(H, T, DupAcc, Acc);
same_order_duplicates_(H, [{H,_}|T], DupAcc, Acc) ->
same_order_duplicates_(H, T, [H|DupAcc], Acc);
same_order_duplicates_(_, [{H,_}=H0|T], DupAcc, Acc) ->
same_order_duplicates_(H, T, DupAcc, [H0|Acc]).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment