The stupid question is the question not asked PerlMonks

### comment on

 Need Help??

Hi

This one's bugged me before, but I think you can do it with full accuracy by creating a hash where the keys represent the bounds between different probabilities. For speed, I'm checking the most likely results first in the second iteration:

```
sub weightedprob {
my %bias = @_;
my (\$total, %boundaries);

# prepare the boundary map
foreach ( sort { \$bias{\$b} <=> \$bias{\$a} } keys %bias ) {
\$total              += \$bias{\$_};
\$boundaries{\$total} = \$_;
}

# get a random place on the boundary map, look it up
my \$random = rand(\$total);
foreach ( sort { \$a <=> \$b } keys %boundaries ) {
return \$boundaries{\$_} if \$random < \$_;
}
}

my \$result = weightedprob(
1 => 3.1,
2 => 2.0234,
3 => 1.7,
4 => 1.542232,
5 => 1.321249563,
6 => 1.0142,
);

I'm not sure if there's a neater way of doing it without having to iterate the hash twice; maybe not, as you need to know the aggregate value of all the values of the weighted die first.

Update: yep, there is a way, as IO ably demonstrated above. I didn't quite see how his/her algorithm was intended. It's shorter, and faster (by about three times, by my Benchmark). I'll doze off again.

//=\\

In reply to Re: Rolling a biased die by ViceRaid
in thread Rolling a biased die by MeowChow

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

• Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
• Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
• Read Where should I post X? if you're not absolutely sure you're posting in the right place.
• Posts may use any of the Perl Monks Approved HTML tags:
a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
• You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
 For: Use: & & < < > > [ [ ] ]
• Link using PerlMonks shortcuts! What shortcuts can I use for linking?

Create A New User
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others exploiting the Monastery: (3)
As of 2019-10-17 05:16 GMT
Sections?
Information?
Find Nodes?
Leftovers?
Voting Booth?
In 2019 the site I miss most is:

Results (42 votes). Check out past polls.

Notices?