in reply to printing all combinations of an array..
For n items there are 2^n combinations. Create a binary string for each combination number. Check each digit of the binary string to determine if the corresponding item gets printed.
YuckFoo
#!/usr/bin/perl use strict; my (@list) = qw(one two three four); printcombo(\@list); #----------------------------------------------------------- sub printcombo { my ($list) = @_; my (@print, $str, $i, $j); my $size = @{$list}; for ($i = 0; $i < 2**$size; $i++) { $str = sprintf("%*.*b", $size, $size, $i); @print = (); for ($j = 0; $j < $size; $j++) { if (substr($str, $j, 1)) { push (@print, $list->[$j]); } } print join(' ', @print) . "\n"; } }
|
---|
Replies are listed 'Best First'. | |
---|---|
Re: Re: printing all combinations of an array..
by Anonymous Monk on Feb 20, 2002 at 04:15 UTC |