I actually did something like this. I had an array,
which described the probability of one of five (in this contrived case) options.my @prob = (0.1, 0.25, 0.03, 0.4, 0.22);
my @options = qw(monday tuesday wednesday thursday friday);
My suggestion is something like this:
#!/usr/bin/perl use strict; use warnings; my @likelihood = (1,3,4,9); my @option = qw(foo bar baz quux); my @sum; $sum[0] = $likelihood[0]; foreach my $n ( 1 .. $#likelihood){ $sum[$n] = $sum[$n - 1] + $likelihood[$n]; } # @sum = (1, 4, 8, 17); my $n = int(rand($sum[-1])+0.1); # random number <= 17 foreach my $i ( 0 .. $#sum) { if($n <= $sum[$i]){ print $option[$i] . "\n";; last; } }
NOTE: This code is not tested.
emc
At that time [1909] the chief engineer was almost always the chief test pilot as well. That had the fortunate result of eliminating poor engineering early in aviation.
—Igor Sikorsky, reported in AOPA Pilot magazine February 2003.In reply to Re: Picking a random item through probability
by swampyankee
in thread Picking a random item through probability
by muba
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |