Created
November 20, 2011 08:14
-
-
Save huynhjl/1379970 to your computer and use it in GitHub Desktop.
brain teaser on missing and duplicated number
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
import util.Random | |
// setup: | |
val size = 1e6.toInt | |
val sorted = (1 to size).toIndexedSeq | |
val missing = Random.nextInt(size) + 1 | |
val duplicated = Random.nextInt(size) + 1 | |
val input = Random.shuffle(sorted.filter(_ != missing) :+ duplicated) | |
// find x and y: | |
val sortedInput = input.sorted | |
val map = sortedInput.sliding(2).collect{ | |
case Seq(a, b) if a == b => "dup" -> a | |
case Seq(a, b) if b == a + 2 => "missing" -> (a + 1) | |
}.toMap | |
printf("missing is %d (expected %d)%n", map.get("missing").getOrElse(-1), missing) | |
printf("duplicated is %d (expected %d)%n", map.get("dup").getOrElse(-1), duplicated) | |
// takes less than 6 seconds |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment