Random value from enum with probability

前端 未结 7 987
既然无缘
既然无缘 2020-12-20 21:40

I have an enum that I would like to randomly select a value from, but not truly random. I would like some of the values to be less likely of being selected so far. Here is

7条回答
  •  不知归路
    2020-12-20 22:08

    You can use EnumeratedDistribution from the Apache Commons Math library.

    EnumeratedDistribution distribution = new EnumeratedDistribution<>(
            RandomGeneratorFactory.createRandomGenerator(new Random()),
            List.of(
                    new Pair<>(Type.TYPE_A, 0.2), // get TYPE_A with probability 0.2
                    new Pair<>(Type.TYPE_B, 0.5), // get TYPE_B with probability 0.5
                    new Pair<>(Type.TYPE_C, 0.3)  // get TYPE_C with probability 0.3
            )
    );
    
    Type mySample = distribution.sample();
    

提交回复
热议问题