如何避免二维数组重复数字? Bingo卡生成器代码排重求助
解决Bingo卡生成器的数字重复问题
你的代码目前的问题是:生成随机数字时没有校验当前行内是否已存在该数字,导致同一行出现重复的1-90范围内的数值。以下是修改后的代码,确保每行包含4个0和5个互不重复的随机数:
方案一:用Set跟踪已生成的数字
import java.util.Random; import java.util.HashSet; import java.util.Set; public class BingoCardGenerator { public static Integer[][] generateBingoCard() { int numRows = 3; int numCols = 9; int randomNumbersPerRow = 5; int randomNumberBound = 90; Random random = new Random(); Integer[][] bingoCard = new Integer[numRows][numCols]; for (int row = 0; row < numRows; row++) { // 初始化当前行为0 for (int col = 0; col < numCols; col++) { bingoCard[row][col] = 0; } Set<Integer> usedNumbers = new HashSet<>(); int assignedCount = 0; while (assignedCount < randomNumbersPerRow) { // 随机选一个未被赋值的列 int indexToAssign = random.nextInt(numCols); if (bingoCard[row][indexToAssign] != 0) { continue; } // 生成不重复的随机数 int numToAssign; do { numToAssign = random.nextInt(randomNumberBound) + 1; } while (usedNumbers.contains(numToAssign)); bingoCard[row][indexToAssign] = numToAssign; usedNumbers.add(numToAssign); assignedCount++; } } // 打印卡片 for (int row = 0; row < numRows; row++) { for (int col = 0; col < numCols; col++) { System.out.printf("%2d ", bingoCard[row][col]); } System.out.println(); } return bingoCard; } public static void main(String[] args) { generateBingoCard(); } }
关键改动:
- 每行新增
Set<Integer> usedNumbers,用于记录当前行已生成的随机数,避免重复 - 生成数字时通过
do-while循环确保新数字不在usedNumbers中 - 用
assignedCount跟踪已成功赋值的数字数量,确保每行刚好生成5个不重复数
方案二:先生成不重复随机数集合再分配
这种方式效率更高,适合范围较大的场景:
import java.util.Random; import java.util.ArrayList; import java.util.Collections; import java.util.List; public class BingoCardGenerator { public static Integer[][] generateBingoCard() { int numRows = 3; int numCols = 9; int randomNumbersPerRow = 5; int randomNumberBound = 90; Random random = new Random(); Integer[][] bingoCard = new Integer[numRows][numCols]; for (int row = 0; row < numRows; row++) { // 初始化当前行为0 for (int col = 0; col < numCols; col++) { bingoCard[row][col] = 0; } // 生成1-90的列表并打乱 List<Integer> numbers = new ArrayList<>(); for (int i = 1; i <= randomNumberBound; i++) { numbers.add(i); } Collections.shuffle(numbers, random); // 随机选5个不同的列 List<Integer> cols = new ArrayList<>(); for (int i = 0; i < numCols; i++) { cols.add(i); } Collections.shuffle(cols, random); // 给选中的列赋值不重复的随机数 for (int i = 0; i < randomNumbersPerRow; i++) { int colIndex = cols.get(i); bingoCard[row][colIndex] = numbers.get(i); } } // 打印卡片 for (int row = 0; row < numRows; row++) { for (int col = 0; col < numCols; col++) { System.out.printf("%2d ", bingoCard[row][col]); } System.out.println(); } return bingoCard; } public static void main(String[] args) { generateBingoCard(); } }
关键改动:
- 每行先创建1-90的完整列表,打乱后取前5个,天然保证不重复
- 同时创建列索引列表并打乱,取前5个列来赋值,确保列不重复
- 避免了循环校验的开销,逻辑更清晰
内容的提问来源于stack exchange,提问作者Daniel Requena
相关产品推荐
相关产品推荐

