生成随机红包数组算法(含最大值最小值限定)

代码

private List<Integer> splitRedPacket(int total, int count, int min, int max) {
    List<Integer> list = new LinkedList<>();
    Random random = new Random();
    // 先预留出最小值保底
    int lastTotal = total - count * min;
    // 剩余钱为0,则不随机
    if (lastTotal == 0) {
      for (int i = 0; i < count; i++) {
        list.add(min);
      }
      return list;
    }
    // 判断是否根据平均值随机
    boolean avgRandom = lastTotal / count > 0;
    // 随机剩余的钱
    for (int i = count; i > 1; i--) {
      // nextInt需要保证参数>0,故通过avgRandom判断采用具体的随机方式
      int value = avgRandom ? random.nextInt(lastTotal / i * 2) : random.nextInt(lastTotal);
      // 随机值保证在最小值最大值区间范围内
      value = Math.max(value, 0);
      value = Math.min(value, max - min);
      lastTotal -= value;
      list.add(value + min);
    }
    if (lastTotal + min > max) {
      // 最后一个红包不满足最小值最大值范围时重新随机
      return this.splitRedPacket(total, count, min, max);
    }
    list.add(lastTotal + min);
    // 乱序保证随机性
    Collections.shuffle(list);
    return list;
  }

注意点

  1. 随机金额时,需要注意入参total传入时将分转为整数,total = total * 100
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值