All Downloads are FREE. Search and download functionalities are using the official Maven repository.

cn.handyplus.lib.util.LotteryUtil Maven / Gradle / Ivy

The newest version!
package cn.handyplus.lib.util;

import cn.handyplus.lib.core.CollUtil;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
 * 区段概率工具类
 *
 * @author handy
 */
public class LotteryUtil {

    private final List lotteryList = new ArrayList<>();
    private double maxElement;

    /**
     * 初始化概率
     *
     * @param list 概率集合
     */
    public LotteryUtil(List list) {
        if (CollUtil.isNotEmpty(list)) {
            double minElement;
            LotteryUtil.ContinuousList continuousList;
            for (Double d : list) {
                minElement = this.maxElement;
                this.maxElement += d;
                continuousList = new ContinuousList(minElement, this.maxElement);
                this.lotteryList.add(continuousList);
            }
        } else {
            throw new IllegalArgumentException("抽奖集合不能为空!");
        }
    }

    public int randomIndex() {
        int index = -1;
        Random r = new Random();
        double d = r.nextDouble() * this.maxElement;
        if (d == 0.0D) {
            d = r.nextDouble() * this.maxElement;
        }
        int size = this.lotteryList.size();
        for (int i = 0; i < size; ++i) {
            LotteryUtil.ContinuousList cl = this.lotteryList.get(i);
            if (cl.isContainKey(d)) {
                index = i;
                break;
            }
        }
        if (index == -1) {
            throw new IllegalArgumentException("概率集合设置不合理!");
        } else {
            return index;
        }
    }

    private static class ContinuousList {
        private final double minElement;
        private final double maxElement;

        public ContinuousList(double minElement, double maxElement) {
            if (minElement > maxElement) {
                throw new IllegalArgumentException("区间不合理,minElement不能大于maxElement!");
            } else {
                this.minElement = minElement;
                this.maxElement = maxElement;
            }
        }

        public boolean isContainKey(double element) {
            return element > this.minElement && element <= this.maxElement;
        }
    }

}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy