mardi 21 décembre 2021

Random changing weight

I need to implement a class where I am able generate random element based on their weight. The tricky part is that I also need to be able to change the weight.

Here is an example output

set_weight("A", 4.0)
set_weight("B", 6.0)
get_random() # return "A" 40% probability, "B" 60%
set_weight("A", 3.0)
get_random() # return "A" 33% probability, "B" 66%

My approach to solving is to find the prefix sum every time a weight is added and append the (element, current_sum_weight) tuple into the list. For set_weight("A", 4.0) and set_weight("B", 6.0), the array would be [("A", 4.0), ("B", 10.0)] Then I generate a random number between 0 and the current sum then iterate through the array to find the first sum weight that is less than the random number and return that element.

However, I don't know how to update the sum weight, because then I would have to iterate through the array and then find the element and update all the weight of elements after. What is a way that I can implement an update for the weight?

I don't know if using dictionary is better, or maybe I should use an ordered dictionary.




Aucun commentaire:

Enregistrer un commentaire