Skip to content

Instantly share code, notes, and snippets.

@daithiocrualaoich
Last active December 21, 2015 10:48
Show Gist options
  • Save daithiocrualaoich/6294156 to your computer and use it in GitHub Desktop.
Save daithiocrualaoich/6294156 to your computer and use it in GitHub Desktop.
Intersection for ordered lists.
def intersect(ens: List[Int], ems: List[Int]): List[Int] = (ens, ems) match {
case (Nil, _) => Nil
case (_, Nil) => Nil
case (en :: ensTail, em :: emsTail) if en == em => en :: intersect(ensTail, emsTail)
case (en :: ensTail, em :: _) if en < em => intersect(ensTail dropWhile { _ < em }, ems)
case (en :: _, em :: emsTail) => intersect(ens, emsTail dropWhile { _ < en })
}
intersect(List(1, 2, 3, 4), List(3, 4, 5, 6)) // = List(3, 4)
intersect(List(3, 4, 5, 6), List(1, 2, 3, 4)) // = List(3, 4)
intersect(List(1, 2, 3, 4), List(1, 2, 3, 4)) // = List(1, 2, 3, 4)
intersect(List(1, 2, 3, 4), List(5, 6, 7, 8)) // = List()
intersect(List(1, 3, 5, 7), List(2, 4, 6, 8)) // = List()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment