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 | |
by tye (Sage) on Jan 27, 2014 at 07:06 UTC | |
by crunch_this! (Acolyte) on Jan 27, 2014 at 21:13 UTC |