Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

It's been a while since I've done this, and I'm embarrassed to ask but here goes: I'm trying to come up with a simple math expression to capture a numeric sequence using the "%" (modulus operator). I'm trying to capture two patterns the first being:
2,7,12,17...
and the second being:
3,8,13,18...
my thoughts are:
[(8%3) += 5] [(8%3) += 6]
This works fine but I have to look at this expression for every iteration of a while loop so I need some way of retaining the value for each comparison, and it doesn't capture the first 2 or 3 values
Any thoughts?

Replies are listed 'Best First'.
Re: What should be an easy math question using %
by Zaxo (Archbishop) on Sep 10, 2003 at 13:12 UTC

    Was the answer something like these?

    my @first = map { 5 * $_ + 2 } 0..3; my @second = map { 5 * $_ + 3 } 0..3;
    You can solve that sort os thing with gcd* of the differences between elements, and then % of any to find the additive part.

    * greatest common divisor

    After Compline,
    Zaxo

Re: What should be an easy math question using %
by broquaint (Abbot) on Sep 10, 2003 at 13:09 UTC
    You could use a closure
    sub seq { my($v, $i) = ($_[0], $_[1] || 5); my $n = 0; return sub { $n ? ($n += $i) : ($n = $v) }; } my $iter = seq 8 % 3, 5; print join ', ' => map $iter->(), 1 .. 5; print " ...\n"; $iter = seq 8 % 5; print join ', ' => map $iter->(), 1 .. 5; print " ...\n"; __output__ 2, 7, 12, 17, 22 ... 3, 8, 13, 18, 23 ...
    So we start out with the initial value of the first argument and then increment by the second argument or 5 by default.
    HTH

    _________
    broquaint

    update: dropped block as first argument as it was rather unnecessary

Re: What should be an easy math question using %
by Anonymous Monk on Sep 10, 2003 at 12:47 UTC
    I think I jumped the gun, I just found a solution. Sorry to have wasted your time with this post.