Created
May 4, 2012 21:21
-
-
Save leedm777/2597800 to your computer and use it in GitHub Desktop.
Inverse FizzBuzz - see http://www.jasq.org/2/post/2012/05/inverse-fizzbuzz.html
This file contains hidden or 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
object ZzubZzif { | |
val fizzbuzz: PartialFunction[Int, String] = { | |
case x if x % 15 == 0 => "fizzbuzz" | |
case x if x % 5 == 0 => "buzz" | |
case x if x % 3 == 0 => "fizz" | |
} | |
// I'm actually embarrassed that this is the best I can do | |
def zzubzzif(seq: Seq[String]): Seq[Int] = { | |
val fizzbuzzIndexed = new PartialFunction[(Int, Int), (String, Int)] { | |
def isDefinedAt(v: (Int, Int)) = fizzbuzz.isDefinedAt(v._1) | |
def apply(v: (Int, Int)) = (fizzbuzz(v._1), v._2) | |
} | |
val candidates = for { | |
start <- 1 to 15 | |
candidateSeq = Iterator.from(start).zipWithIndex.collect(fizzbuzzIndexed).take(seq.length).toList | |
if candidateSeq.map(_._1) == seq | |
} yield (start, candidateSeq.last._2) | |
if (candidates.isEmpty) { | |
Nil | |
} else { | |
val range = candidates.minBy(_._2) | |
range._1 to (range._1 + range._2) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment