[FB]izzBuzz in Perl
I finally sat down and organized my unsorted bookmarks in Firefox. In doing so I came across Jeff Atwood's blog post describing the FizzBuzz test:
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".
I must have bookmarked the link while preparing for interviews before graduation. After skimming over the material I was curious to know the smallest amount of Perl code I could use to write a solution.
Here's my attempt:
Any shorter solutions? I suppose I could just use print if I wanted a one-liner...
It's interesting that you are going for the shortest solution. Jeff's post describes a test for hiring programmers. If I were to hire somebody, I'd put all my bets on the candidate delivering the cleanest code and I'd give lots and lots of bonus points if that code was accompanied by unit tests.
You can replace the first two tests with:
!(%_ % 15)
Or (slightly more self-documenting):
!($_ % (3*5))
As someone else has pointed out, brevity is not necessarily what you want to be optimizing for. That said:
say(('Fizz')[$_%3].('Buzz')[$_%5]or$_) for 1..100;
Throws warnings, though.
Slightly longer and uglier, no warnings:
say((('Fizz')[$_%3]||'').(('Buzz')[$_%5]||'')or$_) for 1..100;
I quite like:
say ("Fizz"x!($_%3)."Buzz"x!($_%5)or$_) for 1..100
Are we allowed to use CPAN
I'm not even going to check CPAN, I'm sure there will be an implementation there :-)More p5 & p6 versions at Rosetta Code -
http://rosettacode.org/wiki/FizzBuzz#Perl
Slightly shorter and uglier with no strict subs:
Yes, I would much prefer someone writing clean code to do this in an interview, but I needed to scratch an itch.
Wow, I suspected concatenation was the key to getting a shorter line, but did not know how to implement it until now. Thanks all for the replies.
I was trying something different here. Didn't work out as concise as I'd hoped, but it's pretty cute...
Along similar lines; a little shorter...
I'm late to the party, but here's my version, using a slightly different approach:
say+(Fizz)[++$_%3].Buzz x/.?[50]$/||$_ until$`