eric256 has asked for the wisdom of the Perl Monks concerning the following question:
Playing with pugs I decided to tackle combinations in a perl6-ish way if i could manage. So I took the binary counting method and applied it. I think the results worked out pretty well but i'm still left betting there is an easier method. What do you think? What could be done different? SVN Version of the code
sub combinations returns Array (@list is rw) { return () unless @list.elems; my @ans; for 1 .. 2**@list.elems-1-> $num { push @ans, [ @list[ (0 .. sqrt($num)).grep:{ $num +& (2**$_) } ] + ]; } return @ans; } my @list = (1..4); combinations(@list).perl.say; __OUTPUT__ ([1], [2], [1, 2], [3], [1, 3], [2, 3], [1, 2, 3], [4], [1, 4], [2, 4] +, [1, 2, 4], [3, 4], [1, 3, 4], [2, 3, 4], [1, 2, 3, 4])
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: P6: Combinations Solution
by kvale (Monsignor) on May 20, 2005 at 06:42 UTC | |
by eric256 (Parson) on May 20, 2005 at 06:58 UTC | |
by kvale (Monsignor) on May 20, 2005 at 07:27 UTC | |
|
Re: P6: Combinations Solution
by revdiablo (Prior) on May 20, 2005 at 16:22 UTC | |
by eric256 (Parson) on May 21, 2005 at 20:27 UTC | |
by revdiablo (Prior) on May 22, 2005 at 23:29 UTC |