Skip to content

Instantly share code, notes, and snippets.

@ianbattersby
Created March 19, 2013 23:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save ianbattersby/5201036 to your computer and use it in GitHub Desktop.
Save ianbattersby/5201036 to your computer and use it in GitHub Desktop.
Fizzbuzz in Kotlin
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()
}
)
}
}
@abreslav
Copy link

If you want to go from 0 to 100? you can just say 0..100

@abreslav
Copy link

Also, when (true) {...} is not needed: use when {...}

@abreslav
Copy link

You can say it divides 15 instead of it.divides(15)

@abreslav
Copy link

"$i" instead i.toString()

@abreslav
Copy link

The Haskell version here doesn't have println(), so for a fair comparison you could use the map() function instead of forEach(), as Neil does.

@melston
Copy link

melston commented Mar 23, 2016

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:

    generateSequence(1 to "") { it.first+1 to "" }.map {
        if(it.first.divides(3)) it.first to it.second+"fizz" else it
    }.map {
        if(it.first.divides(5)) it.first to it.second+"buzz" else it
    }.map {
        if(it.first.divides(7)) it.first to it.second+"bang" else it
    } .map {
        if (it.second.isEmpty()) it.first.toString() else it.second
    }.take(110).forEach {
        println (it)
    }

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 or sequence).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment