Solved Random chance summing to 1

Discussion in 'Spigot Plugin Development' started by Popo121, May 3, 2021.

  1. Hello,

    Let's say I have three items that I want to randomly give to a player. I understand how I would go about randomly giving them if I want them to have an equal chance of being dropped, but what if I want to have a 20% chance for one, 50% for another and 30% for the final item (for example)? I'm storing these items in a list of custom objects that each have a chance property. The sum of the chance properties in the list should add to 1.
     
  2. You basically add up all the weights for each item, and then pick a random number in that range.

    For example, if I had four items with the following weights: 20, 25, 60, 40 (I know this doesn't add to 100, but if you want to make it easier on yourself to mentally know the probabilities, then you can make the sums add to 100). If I add those weights up, I get 145. Next a pick a number from 1-145. Let's say I get 47. We just keep subtracting the weight numbers from the start until we are at 0 or lower, and then that is our item/prize. So 47 - 20 = 27, so we keep going. 27 - 25 = 2, so we go to the next item, 2 - 60 = -58. Now we are at 0 or below so this is item we choose.

    At least that's how I would do it.