Created
March 19, 2013 23:18
-
-
Save ianbattersby/5201036 to your computer and use it in GitHub Desktop.
Fizzbuzz in Kotlin
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
inline fun Int.divides(d: Int) : Boolean { return this % d == 0 } | |
fun main(args: Array<String>) : Unit { | |
var i = 0 | |
iterate { i++ } take 100 forEach { | |
println( | |
when (true) { | |
it.divides(15) -> "fizzbuzz" | |
it.divides(3) -> "fizz" | |
it.divides(5) -> "buzz" | |
else -> i.toString() | |
} | |
) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I came up with a somewhat different approach since one expression of the problem I saw extended it to multiples of 7 with the string "bang" and that began to blow up with the approach above. I used a sequence with map functions as follows:
I start with a Pair<Int, String> and generate a sequence and map over the sequence adding the appropriate strings (or not, as applicable). Then take 110 elements (to get at least one value with all three strings in it) and print each one.
Of course, the first three
map
lambdas are very similar and can be refactored to a function...BTW, this is valid for Kotlin 1.0.0+ (
generateSequence
vs.iterate
orsequence
).