Beefy Boxes and Bandwidth Generously Provided by pair Networks
laziness, impatience, and hubris
 
PerlMonks  

Re: printing all combinations of an array..

by YuckFoo (Abbot)
on Feb 19, 2002 at 20:50 UTC ( #146434=note: print w/replies, xml ) Need Help??


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!

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://146434]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others romping around the Monastery: (4)
As of 2019-12-15 23:03 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found

    Notices?