1.设计一个函数能把给定数组的顺序完全随机打乱
2.给定一个拼手气红包总金额s 和 红包个数n 设计一个函数要求返回一个长度为n的数组代表n个金额随机的红包。
// 遍历随机交换
public double[] shuffle(double[] arr) {
for (int i = 0; i < arr.length; i++) {
int random = (int) Math.random() * (arr.length - 1);
double temp = arr[i];
arr[i] = arr[random];
arr[random] = temp;
}
return arr;
}
public double[] redpacket(int s, int n) {
double remain = s;
double[] pack = new double[n];
for (int i = 0; i < n - 1; i++) {
double random = random(remain);
// 如果剩下的钱不够没人0.01 或者得到的红包金额为0时重新random
while (remain - random < 0.01 * (n - i) || remain - random == remain) {
random = random(remain);
}
remain -= random;
pack[i] = random;
}
pack[n - 1] = Math.round(remain * 100) / 100.0;
return shuffle(pack);
}
// 返回拼手气红包金额
double random(double remain) {
// Math.random() 返回[0,1) 左闭右开
return Math.round(Math.random() * remain * 100) / 100.0;
}