Random value from enum with probability

前端 未结 7 970
既然无缘
既然无缘 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:05

    You can create an enum with associated data bby provding a custom constructor, and use the constructor to assign weightings for the probabilities and then

    public enum WeightedEnum {
        ONE(1), TWO(2), THREE(3);
        private WeightedEnum(int weight) {
            this.weight = weight;
        }
        public int getWeight() {
            return this.weight;
        }
        private final int weight;
    
        public static WeightedEnum randomType()  {
            // select one based on random value and relative weight
        }
    }
    

提交回复
热议问题