in reply to printing all combinations of an array..

In the spirit of TIMTOWTDI, here's my solution.

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
    In the spirit of TIMTOWDI?

    No.

    That is the spirit of the lazy troll supporter ... providing solutions to FAQ questions easily found when so many have already answered them.

    Teach them How to Read The Friendly Manual.

    Sinners Repent!