in reply to possible combinations in sequence
My basic idea is to map the array indices to bits in a binary number. If a bit is on, you take that element out of the source array. For example:
The algorithm then simply becomes a loop over 1 .. 2**@kw -1, testing the bits for each number.0 = 0b0000 --> {nothing} 3 = 0b0011 --> 'horse:cow' 13 = 0b1101 --> 'horse:dog:cat'
Here's my first implementation of it. It's probably not as efficient as possible yet.
I'm a bit irritated with the number of temporary variables, but I can't think of anything prettier just now. Hope it helps :)sub rhesa { # initial source in sequence order my $source = 'horse:cow:dog:cat'; my @kw = split /:/, $source; my @res; for my $i( 1 .. 2**@kw - 1 ) { my @ar; my $t; while( $i > 0 ) { push @ar, $kw[$t] if $i & 1; $i >>= 1; $t++; } push @res, join ':', @ar; } return @res; }
BTW, a simple Benchmark comparison showed a 200% speed increase over your version.
|
---|
Replies are listed 'Best First'. | |
---|---|
Re^2: possible combinations in sequence
by ikegami (Patriarch) on Jun 09, 2006 at 00:45 UTC | |
by ruzam (Curate) on Jun 09, 2006 at 04:01 UTC | |
by ikegami (Patriarch) on Jun 09, 2006 at 06:07 UTC | |
by rhesa (Vicar) on Jun 09, 2006 at 02:27 UTC | |
by Limbic~Region (Chancellor) on Jun 09, 2006 at 12:49 UTC | |
Re^2: possible combinations in sequence
by liverpole (Monsignor) on Jun 09, 2006 at 00:45 UTC | |
Re^2: possible combinations in sequence
by grinder (Bishop) on Jun 09, 2006 at 05:46 UTC |
In Section
Cool Uses for Perl