Created
November 17, 2015 16:54
-
-
Save lhohan/4eab1c83f7e9e17216b3 to your computer and use it in GitHub Desktop.
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
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