my @array = ( ["foo", 1], ["bar", 3], ["baz", 4], ["quux", 9] ); @array = sort { $a->[1] <=> $b->[1] || $a->[0] cmp $b->[0]} @array; my $sum = 0; $_->[2] = ($sum += $_->[1]) for @array; my $v = int(rand $sum); my $idx = 0; $idx++ while ( $v > $array[$idx][2] ); print $array[$idx][0],"\n";

If the list was really large I'd think about binsearching the results. And if I didn't care about memory (often there is no need to care), then I'd just duplicate the elements into a list and then use a random index into the list. For instance if the list is small there is nothing really wrong with doing the easy thing...

my @list = map { ($_->[0]) x $_->[1] } @array; my $elem = $list[rand @list];

(RAM is cheap.)

---
$world=~s/war/peace/g


In reply to Re: Picking a random item through probability by demerphq
in thread Picking a random item through probability by muba

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.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, 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, summary, 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:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.