crunch_this! has asked for the wisdom of the Perl Monks concerning the following question:

Hi again

I've got this (edit: thx to hdb):

#!/usr/bin/perl -w use strict; use warnings; use Algorithm::Combinatorics qw(combinations); my $rep = 10; my @data = 1..$rep; my $iter = combinations( \@data, 4 ); while( my $p = $iter->next ) { my ( $w, $x, $y, $z ) = @$p; next unless $w-2*$x+$y or $x-2*$y+$z; print "$w, $x, $y, $z\n"; }

& I would love to add something that would tell me how many combinations it has gone through before it's done. A percentage would be ideal. I tried my @all_combinations = combinations(\@data, $k); & then something like $#$p/$#all_combinations which got me a number, but it was the same on every line, I suppose because there are always the same number of elements in @$p. I also don't really want to create a new array to put the combinations in because I'm only planning to use it for seeing how close I am to being done.

Replies are listed 'Best First'.
Re: how to add a counter
by choroba (Cardinal) on May 29, 2013 at 23:09 UTC
    The formula to get the total number of all possible combinations can be found at Wikipedia if you do not remember it. Then just increase a counter for each combination and print the ratio:
    #!/usr/bin/perl use warnings; use strict; use Algorithm::Combinatorics qw(combinations); my $rep = 10; my @data = 1 .. $rep; my $size = 4; my $iter = combinations(\@data, $size); my $maxcount = 1; $maxcount *= $_ for 1 + $rep - $size .. $rep; $maxcount /= $_ for 2 .. $size; my $count = 1; while (my ($w, $x, $y, $z) = @{ $iter->next // [] }) { $count++; next unless $w-2*$x+$y or $x-2*$y+$z; print $count/$maxcount, "\t$w, $x, $y, $z\n"; }
    لսႽ† ᥲᥒ⚪⟊Ⴙᘓᖇ Ꮅᘓᖇ⎱ Ⴙᥲ𝇋ƙᘓᖇ
      That's great, I wouldn't have thought of all that but I can take it from there. I don't know why I got down-voted, maybe it was because I didn't credit hdb like maybe I should have (which I fixed).