线段分割法实现微信抢红包

无意间看到的一种实现抢红包的方法,于是用C++实现了一下。
将一个红包分成 n 份
具体的思路是,将一个红包看作是一个线段,线段的长就是红包总金额,然后在这个线段上随机切 n-1 刀,分成 n 份,然后抢红包的人依次来取即可。

#include <iostream>
#include <vector>
#include <set>
#include <random>
#include <ctime>
using namespace std;

vector<int> wechatredmoney(int money, int count) {
  vector<int> res;
  if (money <=0 || count <=0) {
    return res;
  }
  default_random_engine e;
  e.seed(time(nullptr));
  set<int> s;
  for (int i=0; i<count-1; i++) {
    auto index = e() % money;
    if (index == 0 || s.count(index)) {
      i--;
    } else {
      s.insert(index);
    }
  }
  int front = 0;
  for (auto iter = s.begin(); iter != s.end(); iter ++) {
    res.push_back(*iter - front);
    front = *iter;
  }
  res.push_back(money - front);
  return res;
}

int main() {
  auto moneys = wechatredmoney(100, 10);
  for (const auto &x: moneys) {
    cout << x << endl;
  }
  return 0;
}

关注我的公众号
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值