in reply to How to restrict partitions

#!/usr/bin/perl -w use strict; use Algorithm::Loops qw( NestedLoops ); $| = 1; my @sum= shift || 20; my $terms = shift || 4; print "Ways to get a sum of $sum[0] from $terms unique addends:\n"; my $tries= 0; my $iter= NestedLoops( [ ( sub { my $n = @_ ? 1+$_[-1] : 1; my $t = $terms - @_; my $m = $sum[$#_]/$t-($t-1)/2; return [ $n .. int $m ]; } ) x $terms ], { OnlyWhen => sub { $tries++; 0 == ( $sum[@_]= $sum[$#_] - $_[-1] ) && $terms == @_; }, }, ); my @cnt; my $seq= 0; while( @cnt= $iter->() ) { printf "%d) %s\n", ++$seq, join ' + ', @cnt } print "($tries tries)\n";

- tye        

Replies are listed 'Best First'.
Re^2: How to restrict partitions (NestedLoops)
by crunch_this! (Acolyte) on Jan 27, 2014 at 00:20 UTC

    Instead of printing out the partitions, how could I plug them into (I guess) an array & then use them in a polynomial? What I've been using up to now (thx to hdb months ago) is

    while (my ($x, $y, $z) = @{ $iter->next // [] }) { push @wants, map { { join(', ', $x, $y, $z) => $_ } } grep { is_approximately_an_integer( @$_ ) } [ poly_roots( poly_derivative( # expanded form of x*(x - $x)*(x - $y)*(x - $z) 1, -$x - $y - $z, $x*$y + $x*$z + $y*$z, -$x*$y*$z, 0 ) ) ]; }

    The stuff in the while is from the Algorithm::Combinatorics module & the subroutine goes through the zeros of the polynomial's derivative to pick out the ones that have zeros that are all close enough to an integer. I guess it would be to get the elements of @cnt in the prog above but I'm not sure how to do that. Is it as simple as replacing the $x, $y, $z with $cnt[0], $cnt1, $cnt2 in the code above? Or maybe defining my $x = $cnt[0]?

    (a couple minutes later)

    my @cnt; my $seq= 0; my $x = $cnt[0]; my $y = $cnt[1]; my $z = $cnt[2]; while( @cnt = $iter->() ) { #printf "%d) %s\n", ++$seq, join ' + ', @cnt map { { join(', ', $x, $y, $z) => $_ } } grep { is_approximately_an_integer( @$_ ) } [ poly_roots( poly_derivative( # expanded form of x*(x - $x)*(x - $y)*(x - $z) 1, -$x - $y - $z, $x*$y + $x*$z + $y*$z, -$x*$y*$z, 0 ) ) ]; }

    Actually, now that I've tried that, I get errors in the line with the map & also the following one with the grep saying $x, $y, $z are uninitialized which I don't understand because I set them to be elements of @cnt.

      while( my( $x, $y, $z ) = $iter->() ) {

      - tye        

        I got it working. Thx again! You & hdb are lifesavers :)