Skip to content

Instantly share code, notes, and snippets.

@dhedlund
Created February 29, 2012 05:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dhedlund/1938130 to your computer and use it in GitHub Desktop.
Save dhedlund/1938130 to your computer and use it in GitHub Desktop.
PDXErlang intersection implementation w/ Nick
-module(intersection).
-compile(export_all).
intersection(ListA, ListB) ->
intersection([], ListA, ListB).
intersection(Acc, [], ListB) ->
Acc;
intersection(Acc, ListA, ListB) ->
[A|Rest] = ListA,
Acc1 = case match(A, ListB) of
true -> [A|Acc];
false -> Acc
end,
intersection(Acc1, Rest, ListB).
match(X, []) ->
false;
match(X, [Y|Rest]) when X == Y ->
true;
match(X, [Y|Rest]) ->
match(X, Rest).
@dhedlund
Copy link
Author

The above solution isn't perfect. For example, it returns the intersection list in reverse order.

@dhedlund
Copy link
Author

This gist is in relation to the following "ErlangGames" problem presented at the PDXErlang user group:
https://gist.github.com/1937161

A more efficient solution to the problem, w/ an O(n) runtime, might look like:

intersection(ListA, ListB) -> intersection([], ListA, ListB).
intersection(Acc, [A|As], [B|Bs]) when A == B -> intersection([A|Acc], As, Bs);
intersection(Acc, [A|As], [B|Bs]) when A < B  -> intersection(Acc, As, [B|Bs]);
intersection(Acc, [A|As], [B|Bs]) when A > B  -> intersection(Acc, [A|As], Bs);
intersection(Acc, _, _) -> lists:reverse(Acc).

@built
Copy link

built commented Mar 2, 2012

Clever. I like the decomposition. Worth noting that the given lists also have to be sorted.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment