随机抽奖

/**
 * 经常要从多个选项中随机选择一个,不过,不同选项经常有不同的权重。
 *
 * 比如,给用户随机奖励,
 * 三种面额:1元、5元和10元,权重分别为70、20和10。这个怎么实现呢?
 *
 * 实现的基本思路是,使用概率中的累计概率分布。
 *
 * 以上面的例子来说,计算每个选项的累计概率值,
 * 首先计算总的权重,这里正好是100,每个选项的概率是70%、20%和10%,累计概率则分别是70%、90%和100%
 *
 */
public class Test {
    public static void main(String[] args) {
        Pair[] options = new Pair[] {
                Pair.builder().item("1元").weight(7).build(),
                Pair.builder().item("2元").weight(2).build(),
                Pair.builder().item("10元").weight(1).build()
        };
        WeightRandom rnd = new WeightRandom(options);
        for (int i = 0; i < 10; i++) {
            System.out.print(rnd.nextItem() + " ");
        }
    }
}
@Data
@Builder
public class Pair {

    Object item;

    int weight;
}
public class WeightRandom {

    private Pair[] options;

    private double[] cumulativeProbabilities;

    private Random rnd;

    public WeightRandom(Pair[] options) {
        this.options = options;
        this.rnd = new Random();
        prepare();
    }

    private void prepare() {
        int weight = 0;
        for (Pair pair : options) {
            weight += pair.getWeight();
        }
        cumulativeProbabilities = new double[options.length];
        int sum = 0;
        for (int i = 0; i < options.length; i++) {
            sum += options[i].getWeight();
            cumulativeProbabilities[i] = sum / (double) weight;
        }
    }

    public Object nextItem() {
        double randomValue = rnd.nextDouble();
        int index = Arrays.binarySearch(cumulativeProbabilities, randomValue);
        if (index < 0) {
            index = -index-1;
        }
        return options[index].getItem();
    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值