Skip to content

Instantly share code, notes, and snippets.

@lhohan
Created November 17, 2015 16:54
Show Gist options
  • Save lhohan/4eab1c83f7e9e17216b3 to your computer and use it in GitHub Desktop.
Save lhohan/4eab1c83f7e9e17216b3 to your computer and use it in GitHub Desktop.
def fizzbuzz(s: Int): List[String] = {
// helper method inspired by haskell, cycle a list infinitely,
def cycle(xs: List[String]): Stream[String] = Stream.continually(xs).flatten
val numbers = Stream.from(1)
// a infinite cycle of "", "", "Fizz"
val fizzes = cycle(List("", "", "Fizz"))
// a infinite cycle of "", "", "", "", "Buzz"
val buzzes = cycle(List("", "", "", "", "Buzz"))
// zip the fizzes and buzzes, and concatenate them, result is "", "", "Fizz", "", "Buzz", "Fizz", ...
val pattern = fizzes zip buzzes map { case (f, b) => f + b }
// zip numbers with the pattern, if the pattern is empty keep the number, otherwise keep the pattern
val numbersAndPattern = numbers zip pattern map {
case (n, p) => if (p.isEmpty) n.toString else p
}
numbersAndPattern take s toList
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment