dimmesdale has asked for the wisdom of the Perl Monks concerning the following question:
The function has
a reference to the aforementioned hash
and an array that contains they keys of the hash
What I need from this is to select from the array an element(or this could be thought of as one key from the hash). The trick is, though, that the values from the hash each contain the probability of that key being chosen out of the variable $amnt. Let's assume that $amnt is 100; if $hash{key} equalled 50, key would have a 50/100, or %50 chance of being chosen. I figured out that if I put this:
int(rand(99)) < 50 ? "a" : "b" that a would have a %50 chance of being chosen(or so I think).
The problem is that I do not know what I would need to do to have this work for many(a variable number of) objects. I came up with some code, but it is incomplete becaus I stopped when I discovered the problem. Here it is, however, for what little worth it may be to you:
sub get_cat { #cat stands for category, by the way my($hash,$amnt) = @_; my $code; for(@$cats) { unless($_ eq $cats->[-1]) { $code .= "int(rand($amnt-1))<$hash->{$_}?$_:" } else { $code .= "$hash->{$_};"; } } ...and I planned to eval $code, but I realized the problem }
I realize that there is a %40 of a %50 chance for "b" to be chosen, or so I think, but I want to be able to make the code whereas there is a %50 chance for a, %40 for b, and %10 for c (though this is just an example to explain; I need more general code than this)int(rand(99)) < 50 ? "a" : int(rand(99)) < 40 ? "b" : "c";
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Per cents and Probabilities
by btrott (Parson) on Jun 25, 2001 at 02:28 UTC | |
|
Re: Per cents and Probabilities
by cLive ;-) (Prior) on Jun 25, 2001 at 02:24 UTC | |
|
Re: Per cents and Probabilities
by bikeNomad (Priest) on Jun 25, 2001 at 02:12 UTC | |
|
Re: Per cents and Probabilities
by I0 (Priest) on Jun 25, 2001 at 10:50 UTC |