Created
December 29, 2015 02:03
-
-
Save alexland/e92c033856351e2ce00f to your computer and use it in GitHub Desktop.
fizzbuzz implemented in Scala
This file contains hidden or 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
/** | |
* 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