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, January 31, 2012

Fizz 9 - Fire Ready Aim (Dart)

For this Fizz I choose one of the most recent languages: Google's Dart.  While trolling Google Plus I found this solution by Yosuke Sato.

// fizz buzz
main() {
  for(int i=0;i++<100;)
    print((i%3==0?"Fizz":"")+(i%5==0?"Buzz":"")||i);
}

This is a fairly dense rendering of FizzBuzz and gets right to the point without much ceremony: one loop, one single print statement, and a minimum of braces and parenthesis based on operator order of precedence.

Things get interesting when we encounter the short-circuit or operator.  On the left we have a string type, and on the right we have an integer type.  Java would reject this out of hand because short-circuit logical operations can be applied only to boolean primitive types.  Dart, however, has more in common with JavaScript, and uses an entirely different approach.  First the left hand side is evaluated, and what matters is if it is false-equivilant value:  false, null, zero, or the empty string.  The && operator will return the left side if it is negative, and the || operator will return the right hand side if the left is negative.  With boolean values you get simple solutions.  With string and integer types you get more interesting uses.  Such as using || to resolve defaults and the && operator to null-check complex objects.

As an aside, the dartlang.org sample compiler will refuse to run this FizzBuzz in checked mode.  In unchecked mode it will complain about the types.  Perhaps it does have more in common with Java than I realized at first.

No comments:

Post a Comment