Created
May 23, 2012 17:54
-
-
Save hyone/2776665 to your computer and use it in GitHub Desktop.
Inverse FizzBuzz by Scala
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
object InverseFizzBuzz extends App { | |
implicit def makeSeqSafer[A](xs: Seq[A]) = new { | |
def safeMinBy[B](f: A => B)(implicit cmp: Ordering[B]) = | |
if (xs.nonEmpty) Some(xs.minBy(f)) else None | |
} | |
def solve(words: Seq[String]): Option[(Int, Int)] = { | |
List(3,5,6,9,10,12,15).flatMap { x => | |
val (subseq, pos) = Stream.from(x).collect { | |
case i if i % 15 == 0 => ("fizzbuzz", i) | |
case i if i % 3 == 0 => ("fizz", i) | |
case i if i % 5 == 0 => ("buzz", i) | |
}.take(words.length).toList.unzip | |
if (subseq == words) Some(pos.head, pos.last) else None | |
}.safeMinBy { case (s,e) => e - s } | |
} | |
assert( solve(Seq("fizz")) == Some(3,3) ) | |
assert( solve(Seq("buzz")) == Some(5,5) ) | |
assert( solve(Seq("fizz", "buzz")) == Some(9,10) ) | |
assert( solve(Seq("buzz", "fizz")) == Some(5,6) ) | |
assert( solve(Seq("fizz", "buzz", "fizz")) == Some(3,6) ) | |
assert( solve(Seq("fizz", "fizz")) == Some(6,9) ) | |
assert( solve(Seq("fizz", "fizz", "buzz")) == Some(6,10) ) | |
assert( solve(Seq("fizzbuzz", "fizz")) == Some(15,18) ) | |
assert( solve(Seq("fizzbuzz", "fizzbuzz")) == None ) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment