This is a design pattern I see coming up a lot in game design and game programming. I've written the code in Java, but this is more about algorithm design.
I want my program to go down various path based on a random chance, and I want to be able to specify the chance for each path.
For example, I want the program to randomly choose whether or not someone gets their last name from their father or mother, or neither, with different weightings for each of those paths.
//Last Name
int lastNameProc = rand.nextInt(100);
if(lastNameProc < 6){ //Orphan or Disowned by father
if(lastNameProc < 2) { //Orphan
lName = "Smith";
} else { //Disowned
lName = mother.lastName;
}
} else { //Not Orphan or Disowned
lName = father.lastName;
}
This can also be done with inequalities instead of nested if statements. The problem with doing it that way is that it's not obvious from the else-if clauses what percentage chance an event has of occurring.
Is there a common or better way of doing this?
Another way to phrase this question: If I had a sword in an RPG where on a hit the sword applies one of 4 effects, fire, cold, radiant or necrotic damage, with the probability of each being 0.1, 0.2, 0.2 and 0.5. How would I program this without using nested if statements or inequality based if-else statements. I believe this is called an on-hit proc in game design terms.
My question is quite similar to "Generate A Weighted Random Number" however I am unable to translate the code in the answer because I can't figure out which types to use. It would be nice to see a strongly typed example.
Finally, I'm not sure if these are the correct names for this pattern and I'll edit the title to include the correct words.