前言
【编程思维案例7】模拟双色球
- 需求:
- 投注号码由6个红色球和1个蓝色球组成,红色球号码从1-33中选择,蓝色球号码从1-16中选择
- 中奖规则:
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/1e3e9ab203a88c036cd41690f9d85762.jpeg)
(1/3)随机一组中奖号码的分析:
- 中奖号码由6个红球和1个篮球组成(注意:6个红球不能重复),为了模拟双色球号码的生成,使用选中后从数组中删除,再随机的方式
- 定义方法用于返回一组中奖号码(7个数据),返回的形式是一个整型数组
代码
- 常量(可通过修改常量改变彩票组成,如修改成其他彩票还需修改判断中奖情况中的彩票规则和奖项金额输出部分)
public static final int RED_BALL = 6;
public static final int RED_POND = 33;
public static final int BLUE_BALL = 1;
public static final int BLUE_POND = 16;
public static final int SUM_BALL = RED_BALL + BLUE_BALL;
public static int[] createLotteryNumbers() {
Random r = new Random();
int[] lotteryNumbers = new int[SUM_BALL];
int[] redPond = creatPond(RED_POND);
for (int i = 0, j = RED_POND; i < RED_BALL; i++, j--) {
int index = r.nextInt(j);
lotteryNumbers[i] = redPond[index];
redPond = delArrayElement(redPond, index);
}
int[] bluePond = creatPond(BLUE_POND);
for (int i = RED_BALL, j = BLUE_POND; i < SUM_BALL; i++, j--) {
int index = r.nextInt(j);
lotteryNumbers[i] = bluePond[index];
bluePond = delArrayElement(bluePond, index);
}
return lotteryNumbers;
}
public static int[] creatPond(int n) {
int[] arr = new int[n];
for (int i = 0; i < arr.length; i++) {
arr[i] = i + 1;
}
return arr;
}
public static int[] delArrayElement(int[] arr, int position) {
int[] arr1 = new int[arr.length - 1];
for (int i = 0, j = 0; i < arr.length; i++) {
if (i == position