帮我写个红包算法java
以下是一个简单的红包算法Java实现:
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public class RedEnvelope {
/**
* 发红包算法
*
* @param totalAmount 红包总金额
* @param totalCount 红包数量
* @return 红包金额列表
*/
public static List<Integer> divideRedEnvelope(int totalAmount, int totalCount) {
List<Integer> amountList = new ArrayList<Integer>();
Random random = new Random();
int restAmount = totalAmount;
int restCount = totalCount;
for (int i = 0; i < totalCount - 1; i++) {
int amount = random.nextInt(restAmount / restCount * 2 - 1) + 1;
restAmount -= amount;
restCount--;
amountList.add(amount);
}
amountList.add(restAmount);
return amountList;
}
public static void main(String[] args) {
List<Integer> amountList = divideRedEnvelope(100, 10);
for (Integer amount : amountList) {
System.out.println(amount);
}
}
}
这个算法的原理是:先随机分配前N-1个红包金额,然后把剩余的钱分配给最后一个红包,这样可以保证每个红包的金额有随机性,且总金额不会超过指定的总金额。
原文地址: https://www.cveoy.top/t/topic/bDMW 著作权归作者所有。请勿转载和采集!