Beefy Boxes and Bandwidth Generously Provided by pair Networks
Pathologically Eclectic Rubbish Lister
 
PerlMonks  

Re: Combinatorics problem.

by GrandFather (Saint)
on Dec 11, 2015 at 08:31 UTC ( [id://1149989]=note: print w/replies, xml ) Need Help??


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

Maybe not over efficient, at least on memory, but:

#!/usr/bin/perl use strict; use warnings; my $cards = 5; my $holes = 3; my @arrangements = arrange(0, $cards, $holes); print "@$_\n" for @arrangements; sub arrange { my ($usedHoles, $remainingCount, $totalHoles) = @_; my @arrangements; return [$remainingCount] if ++$usedHoles == $totalHoles; for my $thisCount (1 .. $remainingCount - ($totalHoles - $usedHole +s)) { my @subArrangements = arrange($usedHoles, $remainingCount - $thisCount, $totalHo +les); push @arrangements, map {[$thisCount, @$_]} @subArrangements; } return @arrangements; }

Prints:

1 1 3 1 2 2 1 3 1 2 1 2 2 2 1 3 1 1

Update: avoiding most of the memory usage:

#!/usr/bin/perl use strict; use warnings; my $cards = 5; my $holes = 3; arrange(0, $cards, $holes, ''); sub arrange { my ($usedHoles, $remainingCount, $totalHoles, $prefix) = @_; if (++$usedHoles == $totalHoles) { print "$prefix $remainingCount\n"; return; } for my $thisCount (1 .. $remainingCount - ($totalHoles - $usedHole +s)) { arrange($usedHoles, $remainingCount - $thisCount, $totalHoles, + "$prefix $thisCount"); } }
Premature optimization is the root of all job security

Replies are listed 'Best First'.
Re^2: Combinatorics problem.
by BrowserUk (Patriarch) on Dec 11, 2015 at 09:04 UTC
    Update: avoiding most of the memory usage:

    That's perfect. Thankyou.

    It generates the 462 of my bastard testcase instantly:

    C:\test>1149981-gf -cards=12 -holes=7 | wc -l 462

    I'll probably try and turn it into an iterator once my brain's in gear; but the algorithm is spot on. Thanks again.


    With the rise and rise of 'Social' network sites: 'Computers are making people easier to use everyday'
    Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
    "Science is about questioning the status quo. Questioning authority". I knew I was on the right track :)
    In the absence of evidence, opinion is indistinguishable from prejudice.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others having an uproarious good time at the Monastery: (12)
As of 2024-04-23 14:55 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found