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.

#! /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($_); }
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.

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.

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; }
How would you code this routine? Especially, I'm curious what the perl6 solutions might look like. Gimmé!

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

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • 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:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.