If your array size is always the same, then you can avoid having to regenerate the combinations each time.
In my version above, if you look closely you'll see that I don't permute the array elements. I permute the indices and the use those to slice the array. If your array is always the same size, you can do this once and reuse the indices each time which will save a fairly costly recursive generation each time.
A modified version of the above code to show this
#! perl -slw use strict; use vars qw[ $a $b ]; use List::Util qw[ reduce ]; my @indices = map{ Cnr( $_, 0 .. $#ARGV ) } 2 .. @ARGV; my @hasharray; push @hasharray, { LIST=> [ @$_ ], VALUE=> reduce{ $a + $b } @ARGV[ @$_ ] } for @indices; print "@{ $_->{LIST} } : $_->{VALUE}" for @hasharray; exit; sub Cnr{ my( $n, @r ) = shift; return [] unless $n--; for my $x ( 0 .. ($#_ - $n) ) { push @r, map{ [ $_[$x], @$_ ] } Cnr( $n, @_[ ($x+1) .. $#_ ] ) + ; } return @r; }
If your array size varies, but over a short range, then you could use Memoize to cache the generation and only do it the first time a new array size is encountered.
As Algorithm::ChooseSubsets permutes the array rather than the indices, Memoizing that wouldn't reap the same rewards.
There is also a performance penalty from using OO-style interfaces, especially to inherently procedural algorithms. Most of the time this is pretty insignificant, but when it means issuing a call once each time around a loop instead of once at the top of the loop, then the overhead becomes a burden.
In reply to Re: Re: Re: array problems
by BrowserUk
in thread array problems
by bfish
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |