Beefy Boxes and Bandwidth Generously Provided by pair Networks
laziness, impatience, and hubris
 
PerlMonks  

Re: Seek one liner for distributing an integer

by ysth (Canon)
on Sep 22, 2004 at 05:46 UTC ( [id://392849]=note: print w/replies, xml ) Need Help??


in reply to Seek one liner for distributing an integer

Recommended reading which deals with variations on this problem at length: Calendrical Calculations section 1.12, "Cycles of Years".

Distributing m (here, $num) "evenly" into n (here, scalar(@array)) elements, some will be int(m/n), and m%n will be 1 more than that. So, putting all the extras at the front gives:

my %result; my $num = 13; my @array = qw(a b c d e); @result{@array} = map int($num/@array) + $_ < $num%@array, 0..$#array;
To do it randomly, use @result{shuffle @array} instead.

Spreading them out as evenly as possible gives:

@result{@array} = map int($num/@array) + ($_ * ($num%@array) % @array < $num%@array), 0..$#array;
(See formula 1.57 in the book.)

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://392849]
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: (6)
As of 2024-04-19 12:45 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found