http://www.perlmonks.org?node_id=253373


in reply to Re: Re: Printing combinations, code review request
in thread Printing combinations, code review request

That comment points out a version of the code which instead of using the same array to hold all the elements which we're currently 'on', creates a separate array each time. To use it change the body of the for loop from:

push @$list, $$items[$i]; comb_integral($items, $group - 1, $list, $i + 1); pop @$list;

to the single line:

comb_integral($items, $group - 1, [@$list, $$items[$i]], $i + 1);

And here's the new-improved version which returns the combinations instead of printing them, although it does create and destroy a few anonymous arrays in the process:

#!/usr/bin/perl use strict; use warnings; use Data::Dumper; my @list = (1 .. 5); my $take = 2; my @combs = comb_integral(\@list, $take); for my $comb (@combs) { print "@$comb\n"; } sub comb_integral { my ($items, $group, $next) = @_; $next ||= 0; if ($group == 1) { return map [$_], @$items[$next..$#$items]; } else { my @returns; for my $i ($next..$#$items) { push @returns, map [$$items[$i], @$_], comb_integral($items, $gr +oup - 1, $i + 1); } return @returns; } }

In fact I've just thought of another variant of that, replace the push line in the for loop with:

push @returns, my @combs = comb_integral($items, $group - 1, $i + 1); unshift @$_, $$items[$i] for @combs;

Although some might prefer not to code quite so tersely ;-).

--
integral, resident of freenode's #perl

Update: I've just benchmarked this (as integral2) and don't bother with the variant suggested at the end as it's the slowest of my four versions. This does beat by two earlier ones however. Here's my benchmark results:

Benchmark: running SparkyG, demerphq, integral2, intgrl2_f, intgrl_np, + intgrl_pp, iterative, each for at least 1 CPU seconds... SparkyG: 1 wallclock secs ( 1.06 usr + 0.01 sys = 1.07 CPU) @ 15 +70.09/s (n=1680) demerphq: 1 wallclock secs ( 1.05 usr + 0.02 sys = 1.07 CPU) @ 22 +83.18/s (n=2443) integral2: 2 wallclock secs ( 1.10 usr + 0.02 sys = 1.12 CPU) @ 34 +28.57/s (n=3840) intgrl2_f: 2 wallclock secs ( 1.07 usr + 0.02 sys = 1.09 CPU) @ 29 +00.92/s (n=3162) intgrl_np: 2 wallclock secs ( 1.08 usr + 0.00 sys = 1.08 CPU) @ 31 +10.19/s (n=3359) intgrl_pp: 1 wallclock secs ( 1.05 usr + 0.00 sys = 1.05 CPU) @ 31 +99.05/s (n=3359) iterative: 1 wallclock secs ( 1.04 usr + 0.01 sys = 1.05 CPU) @ 42 +65.71/s (n=4479) Rate SparkyG demerphq intgrl2_f intgrl_np intgrl_pp integr +al2 iterative SparkyG 1570/s -- -31% -46% -50% -51% - +54% -63% demerphq 2283/s 45% -- -21% -27% -29% - +33% -46% intgrl2_f 2901/s 85% 27% -- -7% -9% - +15% -32% intgrl_np 3110/s 98% 36% 7% -- -3% +-9% -27% intgrl_pp 3199/s 104% 40% 10% 3% -- +-7% -25% integral2 3429/s 118% 50% 18% 10% 7% + -- -20% iterative 4266/s 172% 87% 47% 37% 33% +24% --