I have an array char[] Select = {'A','B','C','D','E','F','G','H','I','J'}
and each element in this array has different probability to be selected. For example,
int[] Weight = {10,30,25,60,20,70,10,80,20,30};
My requirement is to select 5 elements from this array and the element with high weight values has higher probability to be selected and these 5 elements should be different.
My plan is first sum the weight
int[] weightSum = {10, 40, 65, 125, 145, 215, 225, 305, 325, 355}
Then I use Random to generate a random number k
in the range of [0,355]. Then looking for the first element which is bigger than k
in the weightSum[]
. This process are repeated 5 times.
The problem is that the element with high probability could be selected multiple times. I try to remove the duplicate elements at each iteration. The duplicates are removed, but element with high weight values are not selected.
How to solve this problem?
thanks.