一、題目
紅包算法,給定一個紅包總金額和分紅包的人數,輸出每個人隨機搶到的紅包數量。
要求:
- 每個人都要搶到紅包,並且金額隨機
- 每個人搶到的金額數不小於1
- 每個人搶到的金額數不超過總金額的30%
例如總金額100,人數10,輸出【19 20 15 1 25 14 2 2 1 1】
輸入例子1:
100 10
輸出例子1:
【19 20 15 1 25 14 2 2 1 1】
二、代碼實現
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.Scanner;
public class GrabRedEnvelope {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
List<Double> list = null;
double money = 0;
Random random = new Random();
while (sc.hasNext()) {
double totalMoney = sc.nextDouble();
int count = sc.nextInt();
list = new ArrayList<>(count);
while (count > 1) {
double max = totalMoney * 0.3;
double r = random.nextDouble();
money = r * max;
if (money < 1) {
money = 1;
} else {
money = Math.floor(money * 100) / 100;
}
list.add(money);
count--;
totalMoney -= money;
}
list.add(Math.floor(totalMoney * 100) / 100);
System.out.println(list);
}
sc.close();
}
}