A simple and efficient method is to build an array of items to pick where each item is replicated the number of times to match it's weighting. (Note: I factored the weights by 5 as that reduces the size of the array.);

Then you just pick (once!) from that array and your guaranteed to get darn close to your chosen weightings:

#! perl -slw use strict; use List::Util qw[ sum ]; our $N ||= 1e3; my %group = ( ad1 => 1, ad2 => 2, ad3 => 4 ); my $t = sum values %group; print "Expected"; for ( sort keys %group ) { printf "$_ to be chosen %f%%\n", $group{ $_ } / $t * 100; } my( $key, $value, @choices ); push @choices, ($key) x $value while ( $key, $value ) = each %group; my %picks; for ( 1.. $N ) { $picks{ @choices[ rand @choices ] } ++; } print "\nActual"; for ( sort keys %picks ) { printf "$_ chosen %f%%\n", $picks{ $_ } / $N * 100; } __END__ C:\test>700683 -N=1e6 Expected ad1 to be chosen 14.285714% ad2 to be chosen 28.571429% ad3 to be chosen 57.142857% Actual ad1 chosen 14.276200% ad2 chosen 28.601600% ad3 chosen 57.122200% C:\test>700683 -N=1e6 Expected ad1 to be chosen 14.285714% ad2 to be chosen 28.571429% ad3 to be chosen 57.142857% Actual ad1 chosen 14.309300% ad2 chosen 28.577100% ad3 chosen 57.113600%

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".
In the absence of evidence, opinion is indistinguishable from prejudice.
"Too many [] have been sedated by an oppressive environment of political correctness and risk aversion."

In reply to Re: Weighted random selection by BrowserUk
in thread Weighted random selection by cosmicperl

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.