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

Re: Weighted random numbers generator

by demerphq (Chancellor)
on Mar 13, 2003 at 23:09 UTC ( [id://242883]=note: print w/replies, xml ) Need Help??


in reply to Weighted random numbers generator

I think the below is functionally the same as yours:

#!perl -l my %weights=(a=>1,b=>2,c=>3); my $max=0; my @values=map { my $range=[ $max, $max+$weights{$_}, $_ ]; $max+=$weights{$_}; $range } keys %weights; foreach (1..100) { my $r=rand($max); $_->[0]<=$r and $r<$_->[1] and print $_->[-1] foreach @values; }

You could binsearch the list instead of linsearching it for a bit of speed up.


---
demerphq

<Elian> And I do take a kind of perverse pleasure in having an OO assembly language...

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://242883]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others romping around the Monastery: (7)
As of 2024-03-28 12:47 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found