I have a list of values or objects, each of them has a priority attribute.
Now, I want to randomly pick a value from the list, a value with higher priority has more chances to be picked up.For example:A(5), B(4), C(4), D(3), E(2), F(1) The list, priority is in brackets.After a 1000 times pick from the list, the count of each value be picked up will probably be:
A: 263, B: 211, C: 211, D: 158, E: 105, F: 52
Now, I want to randomly pick a value from the list, a value with higher priority has more chances to be picked up.For example:A(5), B(4), C(4), D(3), E(2), F(1) The list, priority is in brackets.After a 1000 times pick from the list, the count of each value be picked up will probably be:
A: 263, B: 211, C: 211, D: 158, E: 105, F: 52
In my opinion, this can be solved by mathmatical methodology.First you should put these n objects in an array each with a uniqe index from 0 to n.
int n=...;//the count of these objects
Object [] array=new Object [n];//Maybe array[0]=F, array[5]=A;
Then you should define a formula with can map the priority into a float value in (0,1).
The rule is that the object with the highestpriority will be mapped into a float nearest to the value 1. In the contrary, the lowest priority will be mapped into a float nearest to the value 0.For example:
A(5), B(4), C(4), D(3), E(2), F(1)
then the mapping result may be
A(0.9) B(0.7) C(0.5) D(0.3) E(0.2) F(0.1)
I will defin this value to be priorityValue : float priorityValue=mapping(priority);
That to say after the calculation of mapping method, the priority will be mapped into the float between 0 and 1.
The method will be defined like this:
float mapping(int priority)
and the return value : 0< priorityValue <1The we just use the Math.random() method to generate a random double value between 0 and 1.
Every double figure in (0,1) is generated with the same possibility.
Now we can calculate the final result with following fromula:
int index=(int)(HIGHEST_PRIORITY * Math.random() * priorityValue);
The final result index value will be the exact index of the corresponding object.In a word, the task only leaving you is to define a mapping formula from these priority values into a float value in (0,1), which i think is not very conplex for you.
1. 分别计算x1/(x1+x2+……….+xm),x2/(x1+x2+……….+xm)
将计算结果放出float[m]中,注意仍然按照object[m]中的顺序存放
2. 划定边界
a) 由于float[m]中各元素之和为1,所以在数轴上以元素的值为长度画出各个点如下图所示:
0 点1 点2 点3…………………………. 1 长度为 长度为
float[0] float[1] 依次类推b) 那么显然权值最小的所占的长度最短,权值最大的所占长度最长。然后取随机数x
由于x在0~1之间是均匀分布的,所以相应的在长度长的地方(即权值大的地方)x出现的机率要大,这样就完成了。
c) x落在哪个长度范围之内,就读这个长度对应权值的对象。
d) 解毕