Weighted random selection from array

后端 未结 13 1922
醉酒成梦
醉酒成梦 2020-11-28 03:13

I would like to randomly select one element from an array, but each element has a known probability of selection.

All chances together (within the array) sums to 1.<

13条回答
  •  时光说笑
    2020-11-28 03:25

    I am going to improve on https://stackoverflow.com/users/626341/masciugo answer.

    Basically you make one big array where the number of times an element shows up is proportional to the weight.

    It has some drawbacks.

    1. The weight might not be integer. Imagine element 1 has probability of pi and element 2 has probability of 1-pi. How do you divide that? Or imagine if there are hundreds of such elements.
    2. The array created can be very big. Imagine if least common multiplier is 1 million, then we will need an array of 1 million element in the array we want to pick.

    To counter that, this is what you do.

    Create such array, but only insert an element randomly. The probability that an element is inserted is proportional the the weight.

    Then select random element from usual.

    So if there are 3 elements with various weight, you simply pick an element from an array of 1-3 elements.

    Problems may arise if the constructed element is empty. That is it just happens that no elements show up in the array because their dice roll differently.

    In which case, I propose that the probability an element is inserted is p(inserted)=wi/wmax.

    That way, one element, namely the one that has the highest probability, will be inserted. The other elements will be inserted by the relative probability.

    Say we have 2 objects.

    element 1 shows up .20% of the time. element 2 shows up .40% of the time and has the highest probability.

    In thearray, element 2 will show up all the time. Element 1 will show up half the time.

    So element 2 will be called 2 times as many as element 1. For generality all other elements will be called proportional to their weight. Also the sum of all their probability are 1 because the array will always have at least 1 element.

提交回复
热议问题