算法:设有一条直线,长度发红包的总金额,在直线上随机取size-1个点,相邻两个点之间的距离即表示每个红包的金额。
java实现如下:
public class RandomAmount {
private Random random = new Random();
/**
* 计算随机红包金额
* 算法:设有一条直线,长度totalAmount,在直线上随机取size-1个点,相邻两个点之间的距离即表示每个红包的金额。
* @param size 红包个数
* @param totalAmount 总金额,单位元,保留两位小数
* @return 红包金额列表
*/
public float[] random(int size,float totalAmount) {
int amount = (int)(totalAmount*100);
//个数不能大于金额(分),确保每个红包至少一分钱
if(size > amount) {
return null;
}
List<Integer> sites =new ArrayList<>();
//随机取size-1个1~amount之间的随机整数,并确保没有重复。
for(int i=0;i<size-1;) {
//计算金额随机整数1~amount-1
int tv = random.nextInt(amount-1)+1;
//如果数字已经存在,则丢弃
if(!sites.contains(tv)) {
sites.add(tv);
i++;
}
}
//对金额排序(升序)
sites.sort(new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
return o1.compareTo(o2);
}
});
//将最大金额添加到列表中
sites.add(amount);
int pv = 0;
float[] reslut= new float[size];
//将随机数看成是0~amount直线上的点,每个点之间的距离即表示每个红包金额的大小
for(int i=0;i<sites.size();i++) {
int nv = sites.get(i);
//计算每个红包的金额
reslut[i] = (nv-pv)/100f;
pv = nv;
}
return reslut;
}
/**
* @param args
*/
public static void main(String[] args) {
RandomAmount rp = new RandomAmount();
long s = System.currentTimeMillis();
// for(int i=0;i<100;i++) {
float[] result = rp.random(50, 20);
for(float v: result) {
System.out.println(v);
}
// }
long e = System.currentTimeMillis();
System.out.println("time="+(e-s));
}
}