Skip to content

Instantly share code, notes, and snippets.

@bambuchaAdm
Created January 27, 2017 06:11
Show Gist options
  • Save bambuchaAdm/df5375a7055b4266684208809b400668 to your computer and use it in GitHub Desktop.
Save bambuchaAdm/df5375a7055b4266684208809b400668 to your computer and use it in GitHub Desktop.
Result is (A \ B, B \ A) => should be faster the solution based on collection combinators and for comprehension
private def setsDifferences[A](a: SortedSet[A], b: SortedSet[A]): (Iterable[A], Iterable[A]) = {
require(a.ordering == b.ordering, "Sets must use same ordering")
val ordering = a.ordering
@tailrec
def interLoop(accA: List[A], a: SortedSet[A], b: SortedSet[A], accB: List[A]): (List[A], List[A]) = {
(a.headOption, b.headOption) match {
case (Some(elemA), Some(elemB)) =>
ordering.compare(elemA, elemB) match {
case result if result == 0 => interLoop(accA, a.tail, b.tail, accB)
case result if result > 0 => interLoop(accA, a, b.tail, elemB::accB)
case result if result < 0 => interLoop(elemA::accA, a.tail, b, accB)
}
case (Some(_), None) => (accA ++ a, accB)
case (None, Some(_)) => (accA, accB ++ b)
case (None, None) => (accA, accB)
}
}
interLoop(List.empty[A],a,b,List.empty[A])
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment