php红包平均分配,红包平均分配算法
发布日期:2021-06-24 11:22:21 浏览次数:3 分类:技术文章

本文共 1417 字,大约阅读时间需要 4 分钟。

直接上代码

import java.util.Iterator;

import java.util.TreeSet;

public class Hongbao {

private final int[] moneyList;

private final int number;

private final int totalMoney;

private int cur;

public Hongbao(int number, int totalMoney) {

if (number > totalMoney)

throw new IllegalArgumentException("number <= totalMoney");

this.number = number;

this.totalMoney = totalMoney;

moneyList = new int[number + 1];

TreeSet moneySet = new TreeSet<>();

initial(moneySet);

int i = -1;

Iterator iter = moneySet.iterator();

while (iter.hasNext()) {

moneyList[++i] = iter.next();

}

cur = 0;

}

protected void initial(TreeSet moneySet) {

moneySet.add(0);

moneySet.add(totalMoney);

for (int i = 1; i < number; ++i) {

int tempMoney = rand(totalMoney);

while (moneySet.contains(tempMoney)) {

++tempMoney;

tempMoney %= totalMoney;

}

moneySet.add(tempMoney);

}

}

protected int rand(int n) {

return (int)(Math.random() * (n - 1) + 1);

}

public int getOne() {

return moneyList[++cur] - moneyList[cur - 1];

}

}测试代码

public static void main(String[] args) {

int[] arr = new int[20];

for (int i = 0; i < 20; i++)

arr[i] = 0;

for (int j = 0; j < 4000; ++j) {

Hongbao h = new Hongbao(20, 1000);

for (int i = 0; i < 20; ++i)

arr[i] += h.getOne();

}

for (int i = 0; i < 20; i++)

System.out.println(arr[i]);

}我测试的结果

198741

198305

197537

195746

196592

198304

202119

198655

200099

200290

198616

205446

198713

200420

203392

199065

205758

200732

198460

203010

转载地址:https://blog.csdn.net/weixin_32467749/article/details/116475447 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:linux磁盘的命令是,linux磁盘相关的命令
下一篇:oracle numlist,oracle sql str2numlist numtabletype

发表评论

最新留言

路过按个爪印,很不错,赞一个!
[***.219.124.196]2024年04月26日 04时54分44秒