Skip to content

Instantly share code, notes, and snippets.

@sethetter
Created October 26, 2015 03:12
Show Gist options
  • Save sethetter/93be726688af7714a7a9 to your computer and use it in GitHub Desktop.
Save sethetter/93be726688af7714a7a9 to your computer and use it in GitHub Desktop.
defmodule Sublist do
@doc """
Returns whether the first list is a sublist or a superlist of the second list
and if not whether it is equal or unequal to the second list.
"""
def compare(a, b) do
cond do
a == b -> :equal
a == [] -> :sublist
b == [] -> :superlist
sublist_of(a, b) -> :sublist
sublist_of(b, a) -> :superlist
true -> :unequal
end
end
# Entry point
defp sublist_of(a, b), do: sublist_of(a, b, a, false)
# Start recursing, working through lists together
# If first item of each list is equal, assume we're starting a match
# Change 3rd param (found match boolean) and continue on
defp sublist_of([head_a | tail_a], [head_b | tail_b], a, false) do
case head_a === head_b do
true -> sublist_of(tail_a, tail_b, a, true)
false -> sublist_of([head_a | tail_a], tail_b, a, false)
end
end
# Match has been started, keep checking to see if it continues
defp sublist_of([head_a | tail_a], [head_b | tail_b], [head_oa | tail_oa], true) do
cond do
head_a === head_b -> sublist_of(tail_a, tail_b, [head_oa | tail_oa], true)
head_oa === head_b -> sublist_of(tail_oa, tail_b, [head_oa | tail_oa], true)
true -> sublist_of([head_oa | tail_oa], tail_b, [head_oa | tail_oa], false)
end
end
# If we made it this far, then list A was sublist of list B
defp sublist_of([], [_ | _], _, true), do: true
defp sublist_of([], [], _, true), do: true
defp sublist_of([], _, _, false), do: false
defp sublist_of(_, [], _, _), do: false
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment