Skip to content

Instantly share code, notes, and snippets.

@yuroyoro
Created May 15, 2012 04:13
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save yuroyoro/2699068 to your computer and use it in GitHub Desktop.
Save yuroyoro/2699068 to your computer and use it in GitHub Desktop.
// Inversefizzbuzz
// http://www.jasq.org/2/post/2012/05/inverse-fizzbuzz.html
//
object InverseFizzbuzz extends App {
type E = (String,Int)
def zzubzzif(pattern:Seq[String]) = {
val fizzbuzz = (n:Int) => (n%3, n%5) match{
case (0,0) => ("fizzbuzz", n)
case (0,_) => ("fizz", n)
case (_,0) => ("buzz", n)
case _ => ("", n)
}
def startsWith(stream:Stream[E]) = {
pattern.foldLeft(Option(Seq.empty[Int], stream)){(opt,p) =>
opt.flatMap{ case (rv,st) =>
val head #:: tail = st
val (f,n) = head
if(f == p) Some(rv :+ n, tail) else None
}
}
}
def seak(st:Stream[E]):Seq[Int] = startsWith(st) match {
case Some((rv,st)) => rv
case None => seak(st.tail)
}
val nums = Stream.from(1).map(fizzbuzz).filterNot{case (s,_) => s.isEmpty }
val rv = seak(nums)
(rv.head to rv.last).toList
}
def _p(s:Seq[String]) = {
println("pattern : %s" format (s.map{s => s.mkString("'", "", "'")}))
println(zzubzzif(s))
println("")
}
_p(Seq("fizz"))
_p(Seq("buzz"))
_p(Seq("fizz","buzz"))
_p(Seq("fizz","buzz"))
_p(Seq("buzz","fizz"))
_p(Seq("fizz","buzz","fizz"))
_p(Seq("fizz","fizz"))
_p(Seq("fizz","fizz","buzz"))
// Result:
//
// pattern : List('fizz')
// List(3)
//
// pattern : List('buzz')
// List(5)
//
// pattern : List('fizz', 'buzz')
// List(3, 4, 5)
//
// pattern : List('fizz', 'buzz')
// List(9, 10)
//
// pattern : List('buzz', 'fizz')
// List(5, 6)
//
// pattern : List('fizz', 'buzz', 'fizz')
// List(3, 4, 5, 6)
//
// pattern : List('fizz', 'fizz')
// List(6, 7, 8, 9)
//
// pattern : List('fizz', 'fizz', 'buzz')
// List(6, 7, 8, 9, 10)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment