Coding pattern for random percentage branching?

前端 未结 7 906
再見小時候
再見小時候 2020-12-08 18:26

So let\'s say we have a code block that we want to execute 70% of times and another one 30% of times.

if(Math.random() < 0.7)
    70percentmethod();
else
         


        
7条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-08 18:50

    You could compute the cumulative probability for each class, pick a random number from [0; 1) and see where that number falls.

    class WeightedRandomPicker {
    
        private static Random random = new Random();
    
        public static int choose(double[] probabilties) {
            double randomVal = random.nextDouble();
            double cumulativeProbability = 0;
            for (int i = 0; i < probabilties.length; ++i) {
                cumulativeProbability += probabilties[i];
                if (randomVal < cumulativeProbability) {
                    return i;
                }
            }
            return probabilties.length - 1; // to account for numerical errors
        }
    
        public static void main (String[] args) {
            double[] probabilties = new double[]{0.1, 0.1, 0.2, 0.6}; // the final value is optional
            for (int i = 0; i < 20; ++i) {
                System.out.printf("%d\n", choose(probabilties));
            }
        }
    }
    

提交回复
热议问题