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

解决方案 »

  1.   

    他说他有一个list,里面存了一些object或value,而这些object或value在优先级, 现在要求随机存取list里的object或value,但要求优先级高的被取出的机会多.然后给了个example, 应该明白了吧
      

  2.   

    random ++ high priority
      

  3.   

    It's a common problem but is not a pure problem related with Java.
    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.
      

  4.   

    假设现在有数组object[m] (m>=1),他们的号码分别是x1>x2>x3……….>xm
    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) 解毕