Monday, September 24, 2007

Writing the shortest code

If you have not heard about the web site http://golf.shinh.org, a short introduction. It's a site with a list of programming problems, and people are expected to submit their shortest code to solve the problem with their language of choice.

Just to have some fun, I participated in the "FizzBuzz" category. Basically, all you have to do is: Print integers 1 to 100, but replace multiples of 3 with "Fizz" and multiples of 5 with "Buzz" and multiples of both with "FizzBuzz". Simple right?

Shown below are some of my solutions. How short can you go?

PHP: while($i++<100)echo$i%3?$i%5?$i:'':'fizz',$i%5?'':'buzz',"\n"

C: main(i){while(printf(i%5?i%3?"%d\n":"Fizz\n":"FizzBuzz\n"+(i%3?4:0),i),i++<100);}

This take advantage of ternary operation ?: in C. Also, look at how we can "offset" a static string by using an integer. For example let say u have a character array "Hello" in C. printf("Hello"+1); will print you "ello" on the screen. Pretty nifty no?

No comments: