Over a million developers have joined DZone.

Fizzbuzz Without Ifs in 90 Characters -- I'll Buy You a Beer if You Can Beat It

· Java Zone

Discover how AppDynamics steps in to upgrade your performance game and prevent your enterprise from these top 10 Java performance problems, brought to you in partnership with AppDynamics.

Yesterday I got nerd-sniped into solving the FizzBuzz problem without using if sentences.

Unfortunately, a more careful inspection of the problem specification reveals this solution was incorrect.

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”.

Luckily, that’s a very simple fix:

# codegolf version (90 characters):
[{0:"fizzbuzz"}.get(x%(3*5),{0:"fizz"}.get(x%3,{0:"buzz"}.get(x%5,x)))for x in range(101)]
 
# slightly more readable:
[{0: "fizzbuzz"}.get(x%(3*5), 
                     {0: "fizz"}.get(x%3, 
                                     {0: "buzz"}.get(x%5, x))) 
 for x in range(101)]

There you have it, a solution to the fizzbuzz problem that relies on python’s interactive command line interpreter thingy to do the printing, shaving off 4 characters for print.

The “trick”, if it can be called that, is relying on the native get method to return the correct string or fall back to the default value, which checks for the next string in the if-then-else chain.

I wish never to see code like that in something I have to maintain. Ever.

The challenge

Your challenge, should you choose to accept it, is to produce a shorter fizzbuzz solution without using if sentences. I will buy a bottle of beer for the winner.

The best Scala solution so far is 106 characters, by @HairyFotr:

1 to 100 map(a=>println((a%3,a%5)match{case(0,0)=>"fizzbuzz"case(0,_)=>"fizz"case(_,0)=>"buzz"case _=>a})) /cc

No really, I will send a bottle of beer anywhere in the world if you write a shorter solution. Of course, if feasible, I would prefer to take you out for a beer than use snail mail :)

Beer bottles by photos for fun
 
 

The Java Zone is brought to you in partnership with AppDynamics. AppDynamics helps you gain the fundamentals behind application performance, and implement best practices so you can proactively analyze and act on performance problems as they arise, and more specifically with your Java applications. Start a Free Trial.

Topics:

Published at DZone with permission of Swizec Teller, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}