Just something elementary for a lazy weekend...
An interesting link to Simple Programming Exercises came up on the chatterbox. (Thank you.) Scanning that list, something quickly caught my eye. The problem #5. "Why Hello! I see Dr.Fizz and Dr.Buzz have been making rounds all over the world," I thought to myself, and proceeded to check out the perl solution.
There's the naive approach and a more practical variant. I tried to be concise and expressive, but two issues bother me still. Embedded use of sub arguments ($_[0]) does not look smart; this can be improved with signatures I suppose.#! /usr/bin/perl -wl # sum of the numbers in series 1..n that are multiple of either 3 or 5 use List::Util qw(sum sum0); sub f1 { sum0 grep { $_ % 3 == 0 or $_ % 5 == 0 } 1 .. shift; } sub f2 { sum map { $_ * (map $_*($_+1)/2, int $_[0]/abs)[0] } (3, 5, -15); } # while (<>) {...} for (1 .. 23) { print join ' ', $_, f1($_), f2($_); }
What of the (map ..., $x)[0] construct, however? Using (sub{ ... })->($x) is even more circuitous. Just breaking out the terms probably makes it easier to grok, despite the repetition.
How would you code this routine? Especially, I'm curious what the perl6 solutions might look like. Gimmé!sub f3 { my $n = shift; my $t3 = 3 * int($n/3) * int($n/3 + 1) / 2; my $t5 = 5 * int($n/5) * int($n/5 + 1) / 2; my $t15 = 15 * int($n/15) * int($n/15 + 1) / 2; return $t3 + $t5 - $t15; }
ps. Incidentally, Rosetta Code has a talk page for the FizzBuzz problem. That problem appears to have a problem of getting slightly out of hand.
In reply to Elegantly map fizz to buzz by oiskuu
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |