|
|
|||||||||
|
|||||||||
| |||||||||
|
|
|
| |||||||||
![]() |
|
|
«
Previous Thread
|
Next Thread
»
|
Thread Tools | Search this Thread | Rate Thread | Display Modes |
|
|
|
Stop making mediocre tutorials.The best tutorials are video! Camtasia Studio makes it easy to create engaging, buzz-building screen videos at any size, in any popular format. Download the free trial!
|
|
#1
|
|||
|
|||
|
Function which returns true with a given probability
I need to create a function which returns true with a given probability. For example:
foo(.1) returns true with probability .1 Could someone provide either a ruby implementation or a generic way to do this? |
|
#2
|
||||
|
||||
|
Code:
public boolean foo(double probability) {
return true;
}
![]() Seriously, You've got to specify some more logical requirements than that.
__________________
The day I get my hands on the cookbook it's all over. -nicky |
|
#3
|
|||
|
|||
|
I've said plenty. The technical term for what I have described is weighted random selection. In this case, the selection is between two elements: true and false. The probability p, given as an argument, is the weight assigned to true, and therefore the weight assigned to false is 1-p.
I ended up finding a Ruby implementation of weighted random selection that works for any number of elements; using this, I wrote my function. |
|
#4
|
||||
|
||||
|
Its one of those things you have to read twice. Trust me, he isn't usually so "out-of-it". Also, welcome to Dev Shed =D
__________________
"Java makes impossible things possible, but makes easy things difficult." - Somebody
|
|
#5
|
|||
|
|||
|
Quote:
Agreed. Also, I probably could have done better job explaining what I was looking for. ![]() |
|
#6
|
|||
|
|||
|
Use a PRNG.
Say you take a probability out of 100. So for foo(.1), that's really like saying, I have a random number from 1-100. Is it less than 10? A standard PRNG available in most languages gives you a uniform distribution, so the probability is .1 that the number is less than 10. So look up creating random numbers in Ruby. Generate random number within a range (something like 1-100, 1-1000). Check if random number is less than probability*range. If it is, return true, otherwise return false. |
![]() |
| Viewing: Dev Shed Forums > Programming Languages > Game Development > Function which returns true with a given probability |
| Thread Tools | Search this Thread |
| Display Modes | Rate This Thread |
|
|
|
|