Beefy Boxes and Bandwidth Generously Provided by pair Networks
Keep It Simple, Stupid
 
PerlMonks  

Re: Combinatorics problem. (Updated with more info.)

by hdb (Monsignor)
on Dec 12, 2015 at 17:03 UTC ( [id://1150126]=note: print w/replies, xml ) Need Help??


in reply to Combinatorics problem. (Updated with more info.)

Here is a direct, iterative solution generating the possibilities in reverse lexicographical order (no modules, no waste).

use strict; use warnings; my $base = 1; # minimum of cards per hole sub first { my( $holes, $cards ) = @_; my @c = ($base) x $holes; $c[0] += $cards - $base * $holes; $c[0] >= $base or die "Not enough cards!\n"; return \@c; } sub next_comp { my $c = shift; my $i = 0; $i++ while $i < @$c and $c->[$i] == $base; $i >= @$c-1 and return; $c->[$i+1]++; $c->[0] = $c->[$i] - 1; $c->[$i] = $base if $i > 0; return $c; } @ARGV == 2 or die print "Usage: $0 holes cards\n"; my $c = first( @ARGV ); my $i = 0; print ++$i.": @$c\n"; print ++$i.": @$c\n" while $c = next_comp $c;

This also reminds me of Odometer pattern iterator (in C). (Updated.).

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1150126]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others perusing the Monastery: (6)
As of 2024-03-29 15:20 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found