gpt4 book ai didi

java - 尝试使用嵌套循环获取非重复数字..(二维数组)

转载 作者:行者123 更新时间:2023-12-01 19:53:48 24 4
gpt4 key购买 nike

我正在尝试找出一种方法,将随机数插入到 5x5 的二​​维数组中。我正在开发一款宾果游戏,因此任何人都可以帮助我,我将非常感激。我对 Java 相当陌生,所以任何帮助都会很好。谢谢。

考虑:

boolean matchFound;  // used to track when a repeat is found
int rand; // temporarily store the random number before putting it into the array to check if it's a repeat

Random rn = new Random();
for (int i = 0; i < 25 ; i++) {
rand = rn.nextInt(15) + 1;
matchFound = false; // assume that the number generated is not a repeat
for (int x = 0; x <= 5; x++) {
for (int j = 0; j <= 5 ; ++j){
if (rand == b[x][j]) { // check if the number just generated is a repeat
matchFound = true; // if it is, set the boolean to True and use that after the loop
}
if (matchFound == true) { // if the last number is a repeat, then
i = i - 1; // reduce the loop counter by 1 to go back to that place for the new number
} else {
b[i][j] = rand; // the number was not repeated so insert it.
}
}
}
}

最佳答案

我建议将其视为宾果游戏 - 您有一组数字,将它们随机化,然后为棋盘“选择”数字。我相信宾果游戏的范围是从 1 到 75?但你可以改变这一点。然后只需从 ArrayList 中选取前 25 个数字,它们肯定是随机的,不会以这种方式重复。

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;

public class Test {
public static void main(String[] args){
ArrayList<Integer> bingo = new ArrayList<Integer>();
int[][] b = new int[5][5];

// create a list in order
for (int i = 1; i <= 75; i++) {
bingo.add(i);
}

Collections.shuffle(bingo); // randomize

// Add to the board
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5; j++) {
b[i][j] = bingo.remove(0); // remove the first item in the shuffled list
}
}

System.out.print(Arrays.deepToString(b));
}
}

关于java - 尝试使用嵌套循环获取非重复数字..(二维数组),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59061362/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com