Realize the logic of a lottery: get a shard according to the weight of the task shard

Scenario: A task fragment is randomly generated by doing a task, and the probability of output is calculated by its set weight;

Code:

/**
 * Obtain a fragment according to the weight of the task fragment
 * @return MfxyTaskFragment
 * Description:
 * First calculate the total weight of the prize to be selected. The purpose of this is to set the weight of the prize at will, without having to consider whether the sum of the weights is equal to 100.
 * The random rule is to first generate a random number randomNumber (the generated random number is in the left-open and right-closed interval from 0 to 1),
 * Then respectively calculate the probability and d1 and d1 and d1 and The probability and d2 of all the prizes behind the current prize (including the current prize),
 * Then judge whether the random number generated is between d1 and d2. If it is within this range, the current prize will be drawn.
 */
public MfxyTaskFragment PercentageRandomFragment(List<MfxyTaskFragment> prizes) {
     int random =-2;
     try {
         double sumWeight =0;
         //Calculate the total weight for (MfxyTaskFragment rp_1: prizes){             sumWeight += rp_1.getWeight();
        

        }
        double randomNumber;
        randomNumber = Math.random();
        System.out.println("randomNumber是:" + randomNumber);
        double d1 = 0;
        double d2 = 0;

        for(int i=0;i<prizes.size();i++){
            d2 += Double.parseDouble(String.valueOf(prizes.get(i).getWeight()))/sumWeight;
            if(i==0){
                d1 = 0;
            }else{
                d1 +=Double.parseDouble(String.valueOf(prizes.get(i-1).getWeight()))/sumWeight;
            }
            if(randomNumber >= d1 && randomNumber <= d2){
                random = i;
                System.out.println("d1是:" + d1);
                System.out.println("d2是:" + d2);
                break;
            }
        }
    }catch(Exception e){
        System.out.println(e.getMessage());
        random = -1;
    }
    return prizes.get(random);
}

Guess you like

Origin blog.csdn.net/wangpei930228/article/details/114264915