# Weighted loot table

This topic is 2504 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

Hi all,

I have previously written a spawn system previously that used a weighted selection, that allowed me to specify the likely hood (in arbitrary integer values) that an enemy would spawn. I.e. first enemy may have a low probability of spawning and was assigned a value of 1, whereas enemy two may have a high probability of spawning and is assigned a value of 10.

Only thing is, I can't remember how I implemented it.

ID Probability
1 1
2 2
3 3
4 5

The obvious way would be to generate a random value between 0 and the max probability value, and then check which ID it falls on. This sound reasonable, or is there a well known method for doing this?

##### Share on other sites
If your table contains the probability distribution, then you can easily implement this with a binary search of the cumulative distribution. Accumulate all probabilities

C = [1, 3, 6, 11].

Now generate a random number in the half-open range 0 to 11 (including 0, but excluding 11), and it doesn't matter if it's a random integer or decimal value. Search the vector for the first value that is greater than the randomly generated number. This can easily be done with a linear search, or a binary search if the table is large. The index of that value is the index of the object being randomly selected.

##### Share on other sites
Yup - that is it! Thanks, that's very helpful.

##### Share on other sites
Or, if an object of Probability 5 is 5 times as likely to spawn as an object of probability 1, then you should add all the probabilities, and select a random number form that range. Then, check which value-range it falls in:
 ID Prob Range 1 1 0 2 2 1-2 3 5 3-7 
If you did it using your method, then probability 1, 2 and 3 would be exactly the same (all will only spawn if the random number is exactly that probability). Your probability 5 would have twice the chance of hitting as 1, 2, and 3 (since it would spawn if 4 or 5 is randomly hit). Like this:

 ID Prob Range 1 1 0 2 2 1 3 3 2 4 5 3-4 

1. 1
2. 2
Rutin
19
3. 3
4. 4
khawk
15
5. 5

• 13
• 26
• 10
• 11
• 44
• ### Forum Statistics

• Total Topics
633743
• Total Posts
3013644
×