1、需求
前提:给定各个红包金额的情况下,用户随机抽红包。
方法:用数组存储各金额数据,然后将数组打乱,再直接遍历数组一个个抽(此时金额已经打乱,相当于随机抽)
2、实现方式
1. 随机打乱数组
1.1 需求:当前遍历的数据与它后边的数据随机交换位置
遍历数组中每个位置,每遍历到一个位置,就随机一个索引值出来,让当前位置和该索引值处的数据进行交换。随机的索引值包含当前位置、不包含已经遍历过的位置。
for (int i = 0; i < money.length; i++) {
// money = {4, 666, 6, 520, 999}
// 0 1 2 3 4
int index = r.nextInt(money.length - i) + i;
int temp = money[i];
money[i] = money[index];
money[index] = temp;
// System.out.println(money[i]);
每次运行的结果,都是数组内的元素发生了随机位置变化。
1.2 需求:当前遍历的数据与任意位置处数据随机交换位置。
遍历数组中每个位置,每遍历到一个位置,就随机一个索引值出来,让当前位置和该索引值处的数据进行交换。随机的索引值是任意位置处的索引值,包含当前位置、剩余位置、之前已经遍历过的位置。
for (int i = 0; i < money.length; i++) {
// money = {4, 666, 6, 520, 999}
// 0 1 2 3 4
int index = r.nextInt(money.length);
int temp = money[i];
money[i] = money[index];
money[index] = temp;
// System.out.println(money[i]);
2. 再直接一个个抽,金额已经打乱,相当于随机抽
for (int i = 0; i < money.length; i++) {
System.out.println("请输入任意内容进行抽奖:");
sc.next();
System.out.println("恭喜抽中" + money[i] + "元");
}
抢红包完整代码:
public class Test {
public static void main(String[] args) {
//抢红包
int[] money = {4, 666, 6, 520, 999};
start(money);
}
public static void start(int[] money) {
Random r = new Random();
Scanner sc = new Scanner(System.in);
//1. 打乱金额:遍历数组中每个位置,每遍历到一个位置,就随机一个索引值出来
for (int i = 0; i < money.length; i++) {
// money = {4, 666, 6, 520, 999}
// 0 1 2 3 4
int index = r.nextInt(money.length - i) + i;
int temp = money[i];
money[i] = money[index];
money[index] = temp;
// System.out.println(money[i]);
//2. 直接一个个抽,金额已经打乱,相当于随机抽
System.out.println("请输入任意内容进行抽奖:");
sc.next();
System.out.println("恭喜抽中" + money[i] + "元");
}
System.out.println("本次活动结束啦~");
}
}