ID:195134
 
//Title: Weighted Probability Selection
//Credit to: Jtgibson
//Contributed by: Jtgibson


proc/weightedprob(choices[], weights[])
if(!choices || !weights) return null

//Build a range of weights
var/max_num = 0
for(var/X in weights) if(isnum(X)) max_num += X

//Now roll in the range.
var/weighted_num = rand(1,max_num)

var/running_total, i

//Loop through all possible choices
for(i = 1; i <= choices.len; i++)
if(i > weights.len) return null

running_total += weights[i]

//Once the current step is less than the roll,
// we have our winner.
if(weighted_num <= running_total)
return choices[i]


///*
//Testing code/sample implementation:

mob/proc/test_weighted_prob()
var/weights = list( 5, 10, 20, 40, 20, 15, 10, 5, 2)
var/choices = list("1","2","3","4","5","6","7","8","9")

usr << weightedprob(choices, weights)

//*/