Created
May 15, 2012 21:15
-
-
Save shout-poor/2705207 to your computer and use it in GitHub Desktop.
Inverse Fizzbuzz by k.ONO (shout_poor)
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
/** | |
* Inverse Fizzbuzz | |
* http://www.jasq.org/2/post/2012/05/inverse-fizzbuzz.html | |
**/ | |
object InverseFizzBuzz extends App { | |
val fizzbuzz = new PartialFunction[Int, (Int, String)] { | |
def apply(x:Int) = (x, (x%3,x%5) match { | |
case (0, 0) => "fizzbuzz" | |
case (0, _) => "fizz" | |
case (_, 0) => "buzz" | |
case _ => "" | |
}) | |
def isDefinedAt(x:Int) = (x%3==0 || x%5==0) | |
} | |
def invFizzBuzz(pattern:Seq[String], searchRange: Seq[Int]) = { | |
val (f, e) = searchRange.filter(fizzbuzz.isDefinedAt) | |
.map((x) => Stream.from(x).collect(fizzbuzz)) | |
.map(pattern.zip(_).map(x => (x._2._1, x._1, x._2._2))) | |
.filter(l => l.foldLeft(true) ((z, x) => z && x._2 == x._3)) | |
.map(l => (l.head._1, l.last._1)) | |
.minBy(x => x._2 - x._1) | |
f to e | |
} | |
def _p(s:Seq[String]) = { | |
val rng = 1 to 15 | |
println("pattern : %s" format(s.map(s => s.mkString("'", "", "'")))) | |
println(invFizzBuzz(s, rng)) | |
println("") | |
} | |
_p(Seq("fizz")) | |
_p(Seq("buzz")) | |
_p(Seq("fizz","buzz")) | |
_p(Seq("buzz","fizz")) | |
_p(Seq("fizz","buzz","fizz")) | |
_p(Seq("fizz","fizz")) | |
_p(Seq("fizz","fizz","buzz")) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment