Write a program that prints the numbers from 1 to 100. But for multiples of three print “Fizz” instead of the number and for the multiples of five print “Buzz”. For numbers which are multiples of both three and five print “FizzBuzz”.

Tuesday, February 21, 2012

#13 - When in St. Petersberg

That was a short break. Basically I wasn't liking the structure I was forcing myself into. Once I get a large corpus of solutions I can look into formatting, but in the mean time I will focus on stuff that entertains me, free of schedule constraints or themes.

But last Tuesday JetBrains publicly released the beta of Kotlin, their entry into the alternative not-just-JVM languages. There are several very interesting features of this language. And best of all it runs in an IDE I use on a daily basis: IntelliJ Idea. Since this will be the first of several posts, I will first present the solution that most of them will build on.

fun main(args : Array<String>) {
    for (i in 1..100) {
        when (i%15) {
            0 -> println("FizzBuzz");
            5,10 -> println("Buzz");
            3,6,9,12 -> println("Fizz");
            else -> println(i);
        }
    }
}

Instead of a switch statement Kotlin has a when statement (lines 3-8). This is for the most part syntactic sugar, but real sugar not the high fructose code syrup sold to public school programming students. At first blush it looks like changing the word when for switch and some other changes in the case blocks. And in this example, it is all the same. But it is denser and hence reads better.

First, you will not that there is no implicit fall-through. Each case statement matches up to exactly one expression (and that expression can be a multi-expression block). To fall through the rest of the switch you must explicitly use the continue statement. And even then it will simply continue to evaluate itself against the conditions rather than jump to the next block. So the old-school switch drop throughs which were the source of some mysterious bugs are not longer explicitly allowed.

Second, because of the single use structure of the blocks, multiple cases are combined into one comma-separated expression. This is possible because there is no possibility of fall-through between each label.

Finally, the default case (denoted by the else case) is required except in instances when "the compiler can prove that all possible cases are covered with branch conditions".

For this solution, I took advantage of the 15 number pattern in FizzBuzz and simply switched on the mod of 15. There is one case for a FizzBuzz, two for a Buzz, and four for a Fizz. Everything else falls into the else block. This actually reads fairly close to the text description of the problem statement.

The IntelliJ team writing Kotlin is based mostly in Russia. The name Kotlin is from the name of an island near St. Petersberg, which is not really that close to Rome.

No comments:

Post a Comment