Skip to content

Instantly share code, notes, and snippets.

@alexland
Created December 29, 2015 02:03
Show Gist options
  • Save alexland/e92c033856351e2ce00f to your computer and use it in GitHub Desktop.
Save alexland/e92c033856351e2ce00f to your computer and use it in GitHub Desktop.
fizzbuzz implemented in Scala
/**
* returns a transformed list (of strings) of the
* 1-to-100 integer list passed in such that:
* integers evenly divisible by 3 are replaced by "fizz"
* integers evenly divisible by 5 are replaced by "buzz"
* integers evenly divisible by both 3 & 5 are replaced by "fizzbuz"
* all other integers are replaced by their string representation
* */
def f[Int](q:List[Int]=(1 to 100).toList):List[String] = {
fb.foldLeft(List[String]())( (u, v) =>
v match {
case v if ((v % 3 == 0) && (v % 5 == 0)) => u :+ "fizzbuzz"
case v if (v % 3 == 0) => u :+ "fizz"
case v if (v % 5 == 0) => u :+ "buzz"
case v => u :+ v.toString
}
)
}
scala> val res = f()
scala> res.length
Int = 100
scala> for (itm <- res.slice(1, 20)) println(itm)
2
fizz
4
buzz
fizz
7
8
fizz
buzz
11
fizz
13
14
fizzbuzz
16
17
fizz
19
buzz
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment