Last active
December 21, 2015 10:48
-
-
Save daithiocrualaoich/6294156 to your computer and use it in GitHub Desktop.
Intersection for ordered lists.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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