Skip to main content

Weighted Random

Definition​

The Weighted Random Algorithm is a method used to select elements randomly from a collection, with each element having a weighted probability of being chosen. This algorithm is commonly employed in scenarios where certain elements are more likely to be selected than others based on their assigned weights

Practice​

weighted_random(collection):
cum_weights = calculate_cumulative_weights(collection)
random_num = generate_random_number(0, total_sum(cum_weights))
return select_element(collection, cum_weights, random_num)

calculate_cumulative_weights(collection):
cum_weights = []
cum_weight = 0
for each element in collection:
cum_weight += element.weight
cum_weights.append(cum_weight)
return cum_weights

select_element(collection, cum_weights, random_num):
for i from 0 to length(collection) - 1:
if random_num < cum_weights[i]:
return collection[i]