Hello Monks,
Been through the year 2007'ish thread here about fizzbuzz. Reason: - Just came back from an interview. I had mentioned in my resume that I was doing some sys admin level perl scripting, and one of the interviewers asked me to write a script that would print fizz if the number is divisible by 3, buzz if the number is divisible by 5, and fizzbuzz if it is divisible by both.
I had clearly stated during the interview that I had done perl scripting about 3 years ago, and then didn't much write any scripts, except for a 15 minute fiddle may be once in a month or two.
It did take me about 15-20 minutes to write this script, and I had to look up the documentation (It was stated that I could refer to perldocs). So I came up with the following:
C:\>more newfizzbuzz.pl #!/usr/bin/perl use warnings; use strict; my @stuff = (1..100); my @fizzbuzz = map { ($_ % 3 == 0 && $_ % 5 == 0)?print "fizzbuzz\t": $_ % 3 == 0? print "fizz\t": $_ % 5 == 0?print "buzz\t":print "$_\t" } @stuff;
And here is the output.
C:\>perl newfizzbuzz.pl 1 2 fizz 4 buzz fizz 7 8 fizz + buzz 11 fizz 13 14 fizzbuzz 16 17 fiz +z 19 buzz fizz 22 23 fizz buzz 26 fizz 28 29 fizzbuzz 31 + 32 fizz 34 buzz fizz 37 38 fizz buz +z 41 fizz 43 44 fizz buzz 46 47 fizz 49 buzz fizz 52 53 + fizz buzz 56 fizz 58 59 fizzbuzz 61 + 62 fizz 64 buzz fizz 67 68 fizz buzz 71 fizz 73 74 + fizzbuzz 76 77 fizz 79 buzz fizz 82 + 83 fizz buzz 86 fizz 88 89 fizzbuzz 91 92 fizz 94 + buzz fizz 97 98 fizz buzz
I was asked if there was a better way of doing it and I told that there must be, but that I would have to try it out and see. I was also asked if there was a reason why I didn't use an if/else if statement, and such questions.
So I came up here and did a search for fizzbuzz, and most of the folks have written a oneliner (golf). Just wanted to know if there is something wrong with the script I have given above? Is one liner a preferred way of writing such scripts? Any comments or suggestions would be appreciated.
Note:- Granted that what I've written is not elegant/compact/idiomatic, but just wanted to know if it's so bad that it justifies the weird expression on the interviewer's face? after checking my script :)
In reply to The FizzBuzz Thing :( by Anonymous Monk
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |