Like demerphq I wanted to reduce the ammount of array copying in your code, but I also didn't like the way the input array had to be copied, so I came up with the following (although you may like to change my coding style in places):
#!/usr/bin/perl use strict; use warnings; my @list = (1 .. 5); my $take = 2; comb_integral(\@list, $take); sub comb_integral { my ($items, $group, $list, $next) = @_; $list ||= []; $next ||= 0; if ($group == 1) { my $prefix = join " ", @$list; print "$prefix $_\n" for @$items[$next..$#$items]; } else { for my $i ($next..$#$items) { push @$list, $$items[$i]; # the next line is an alternate which elimates the use of push/pop #comb_integral($items, $group - 1, [@$list, $$items[$i]], $i + 1); comb_integral($items, $group - 1, $list, $i + 1); pop @$list; } } }
--
integral, resident of freenode's #perl
In reply to Re: Printing combinations, code review request
by integral
in thread Printing combinations, code review request
by SparkeyG
For: | Use: | ||
& | & | ||
< | < | ||
> | > | ||
[ | [ | ||
] | ] |