I have a bunch of keys that each have an unlikeliness variable. I want to randomly choose one of these keys, yet I want it to be more unlikely for unlikely (key, values) to
Here is a classic way to do it, in pseudocode, where random.random() gives you a random float from 0 to 1.
let z = sum of all the convictions
let choice = random.random() * z
iterate through your objects:
choice = choice - the current object's conviction
if choice <= 0, return this object
return the last object
For an example: imagine you have two objects, one with weight 2, another with weight 4. You generate a number from 0 to 6. If choice
is between 0 and 2, which will happen with 2/6 = 1/3 probability, then it will get subtracted by 2 and the first object is chosen. If choice is between 2 and 6, which will happen with 4/6 = 2/3 probability, then the first subtraction will still have choice being > 0, and the second subtraction will make the 2nd object get chosen.