views:

45

answers:

2

I'm trying to generate unique permutations of an array using Math::Combinatorics. As CPAN page says it can be done using next_string():

use Math::Combinatorics;
my @arr = [1,1,1,0,0];  
$c = Math::Combinatorics->new( count=>5, data=>[\@arr], frequency=>[3,2] );
while (@permu = $c->next_string()){
print "@permu\n";
}  

However this code gives me the following error: must use next_permutation of 'frequency' argument not passed to constructor and I can't understand why.

+1  A: 

Although I have not used this package the documentation says that frequency must be the same length as the data constructor argument.

In your example the lengths are not the same so may be this is the problem.

rics
+6  A: 

You have a lot of problems in that program. There's a mismatch in your data types.

If you want to use frequency, you only specify the unique elements once but specify how many times they appear. The array reference you give to frequency has to be the same length as your data array:

use Math::Combinatorics;

my @array = (1,0); # an array, not an array reference

$c = Math::Combinatorics->new( 
    count     => 5,
    data      => \@array,        # now you take a reference    
    frequency => [3,2] 
    );

while (@permu = $c->next_string ){
    print "@permu\n";
    }

Now you should get the output you wanted, which are the distinct combinations where you can't tell the difference between the multiple 1's and multiple 0's:

0 1 1 1 0
0 1 1 0 1
0 1 0 1 1
0 0 1 1 1
1 0 1 1 0
1 0 1 0 1
1 0 0 1 1
1 1 0 1 0
1 1 0 0 1
1 1 1 0 0

If you don't use frequency, you just have to specify all the elements in the data array. However, you're probably avoiding that because it treats every element as distinct so it doesn't collapse what look like the same combination.

brian d foy