• Our friends from AlphaCentauri2.info are in need of technical assistance. If you have experience with the LAMP stack and some hours to spare, please help them out and post here.

[Technique Question] Weighted Random Selection

Dom Pedro II

Modder For Life
Joined
Apr 3, 2002
Messages
6,811
Location
Exit 16, New Jersey
I'm trying to come up with a way to create a weighted probability for randomly generated values. For example, if I want the game to pick a technology or unit at random to give to a player, it's easy to have it pick one with an equal chance of selecting any one.

For example, in my Extra Pillage mod, when a pillaged improvement gives research, it checks all the available techs and sees which are elligible, then randomly picks one tech of that shortened list and gives research points towards it.

But what if I want to make it so that there's a 60% chance of it choosing one, and maybe %20 chance of another, 10% of another, etc. etc.

I'm not great with math, so I'm not sure how one would create this kind of system. I've developed a couple of ideas, but none really satisfy me. The best I've come up with so far is adding multipliers for the different choices and then having the game generate a random number for each choice, multiply it by the multiplier and take the largest number. The problem comes in trying to predict the probability of any of the results...
 
Make one random number for the total chance, then give each choice a different number it has to be lower than (or higher than).
Something like this

Code:
a = CyGame().getSorenRandNum(100, "something")
if a < 60: #60% chance (0-59)
        dosomething
elif a < 80: #20% chance (60-79)
        somethingelse
elif a < 90: #10% chance (80-89)
        3rdchoice
else: #10% chance (90-99)
        finalchoice
 
I dunno if it's slow for what you want.. but I found this:

http://hell.org.ua/Docs/oreilly/webprog/pcook/ch02_07.htm

I tried something like (1 => 6, 2 => 2, 3 => 2) "rolling" 10 times in a row and most of the times 1 appears most. I don't know how difficult it would be to do that too, but in python I think it should be easy...

btw, if you're going for SDK
It uses a random number generator with known characteristics using the » Mersenne Twister, which will produce random numbers four times faster than what the average libc rand() provides.
 
Back
Top Bottom