in reply to Re: Recursion problem
in thread Recursion problem

I'm sorry, but I really can't see an elegant way to do a scan of all possible n-ple of an array without using a recursive sub. Can you please give me a hint?

Rule One: Do not act incautiously when confronting a little bald wrinkly smiling man.

Replies are listed 'Best First'.
Re^3: Recursion problem
by Limbic~Region (Chancellor) on May 26, 2008 at 00:10 UTC
    psini,
    You may want to look at Finding all Combinations which has several iterator solutions (including mine). In essence, we want to find all possible combinations (powerset) minus the empty set.

    Iterating over all combinations is as simple as counting. Think of all values in the array to be calculated as being 0s or 1s. If it is a 1, the value is included and if it is 0, it isn't. For instance:

    5 -6 8 10 12 3 10 0 0 0 0 0 0 1 = 10 0 0 0 0 0 1 0 = 3 0 0 0 0 0 1 1 = 3, 10 0 0 0 0 1 0 0 = 12 0 0 0 0 1 0 1 = 12, 10 ... 1 1 1 1 1 1 1 = 5, -6, 8, 10, 12, 3, 10

    #!/usr/bin/perl use strict; use warnings; use List::Util 'sum'; my @amount = (5, -6, 8, 10, 12, 3, 10); my $count = @amount; for (1 .. 2 ** $count - 1) { my @bit = split //, sprintf("%.${count}b", $_); my $total = sum( map {$bit[$_] ? $amount[$_] : 0 } 0 .. $#bit); print "$total\n"; }

    Cheers - L~R

Re^3: Recursion problem
by Erez (Priest) on May 26, 2008 at 06:35 UTC

    I really can't see an elegant way to do a scan of all possible n-ple of an array without using a recursive sub

    Elegance for the sake of elegance is what caused the famous quote about LISP programmers who know the value of everything and the cost of nothing.

    TIMTOWDI, and different algorithms will do. My point being that our OP made a very odd choice for his foray into the world of recursions. There are ways of solving this recursively without blowing up the stack, but for a beginner, this doesn't look like the best thing to start with.

    Stop saying 'script'. Stop saying 'line-noise'.
    We have nothing to lose but our metaphors.