Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl-Sensitive Sunglasses
 
PerlMonks  

comment on

( [id://3333]=superdoc: print w/replies, xml ) Need Help??
Rather late, but I believe this works:
use warnings; use strict; use ntheory qw/forpart/; use List::MoreUtils qw/uniq/; my $sum = shift || 20; my $terms = shift || 4; forpart { print "@_\n" if @_ == uniq @_ } $sum,{n=>$terms};

forpart is a partitions iterator similar to Pari/GP 2.6.1+, either unrestricted or with min/max/exact number of elements / size of elements. Pari/GP has some better optimizations, but even so, restricting the number of elements inside the XS code is a big win.

For cases where the sum and number of desired partitions gets large it helps to be a little smarter. Since we want unique elements, we know sequences like ... 1 1 1 1 1 won't work. The minimum sequence ends with ... 5 4 3 2 1, so we can find out the largest allowed element:

use warnings; use strict; use ntheory qw/forpart/; use List::MoreUtils qw/uniq/; my $sum = shift || 20; my $terms = shift || 4; my $amax = $sum; $amax -= $_ for 1 .. $terms-1; if ($amax > 0) { forpart { print "@_\n" if @_ == uniq @_ } $sum, {n=>$terms, amax=>$amax}; }
I think this is pretty straightforward to use and quite fast for most cases. As the sum goes up much over 100 this can still get out of control (Pari has the same issue). tye's Algorithm::Loops solution is better at weeding out non-uniques early in this case.

In reply to Re: How to restrict partitions by danaj
in thread How to restrict partitions by crunch_this!

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post; it's "PerlMonks-approved HTML":



  • Are you posting in the right place? Check out Where do I post X? to know for sure.
  • Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
    <code> <a> <b> <big> <blockquote> <br /> <dd> <dl> <dt> <em> <font> <h1> <h2> <h3> <h4> <h5> <h6> <hr /> <i> <li> <nbsp> <ol> <p> <small> <strike> <strong> <sub> <sup> <table> <td> <th> <tr> <tt> <u> <ul>
  • Snippets of code should be wrapped in <code> tags not <pre> tags. In fact, <pre> tags should generally be avoided. If they must be used, extreme care should be taken to ensure that their contents do not have long lines (<70 chars), in order to prevent horizontal scrolling (and possible janitor intervention).
  • Want more info? How to link or How to display code and escape characters are good places to start.
Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others drinking their drinks and smoking their pipes about the Monastery: (5)
As of 2024-04-17 21:47 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found