This one only took four hours to get to the first working version. The reason it took me so long is that I wanted to try to do it without doing the same conditional test more than once (also, I'm not good at this). It isn't very obfuscaturated:
#!/usr/bin/perl -w
use strict;
for my $num (1 .. 100) {
my $mod3num = $num % 3;
my $mod5num = $num % 5;
my $result = "";
if ( $mod3num == 0 ) {
$result .= "fizz";
}
if ( $mod5num == 0 ) {
$result .= "buzz";
}
if ( $result =~ /z/ ) {
print "[$num] $result\n";
} else {
print "[$num] $num\n";
}
}
Here's a different one I spent some of that four hours trying to do, then completed in 15 minutes the next day. It seems pretty annoying but I think it could be better:
#!/usr/bin/perl -w
use strict;
for my $n (1 .. 100) {
my $nm3 = $n % 3;
my $nm5 = $n % 5;
print((!$nm3 && !$nm5) ?
"[$n] fizzbuzz\n"
: (!$nm5?
"[$n] buzz\n"
: (!$nm3?
"[$n] fizz\n"
: "[$n] $n\n")))
}
Questions:
- How bad is it?
- How much worse can it be?
- If I did this in an interview, would you hire me?
- Why would you do that to yourself?
- Which version offends the sensibilities more?
- What techniques for making my code more compact and less maintainable have I overlooked?
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.