猿问

如何在2D阵列中选择三个随机点?

我有一些代码可以创建一个2D布尔数组,随机选择3个空格并将它们分配给true。现在,我的代码可能会选择 2 个相同的空格并将其分配给 true,因此我可能不会最终得到 3 个空格为 true。如何更改代码以从数组中选择 3 个随机且唯一的空格?


boolean mineLocations[][] = new boolean[rows][cols];


int rRow = random.nextInt(rows);

int rCol = random.nextInt(cols);

mineLocations[rRow][rCol] = true;


rRow = random.nextInt(rows);

rCol = random.nextInt(cols);

mineLocations[rRow][rCol] = true;


rRow = random.nextInt(rows);

rCol = random.nextInt(cols);

mineLocations[rRow][rCol] = true;


三国纷争
浏览 140回答 3
3回答

哆啦的时光机

下面是一个如何执行此操作的示例:boolean mineLocations[][] = new boolean[rows][cols];Random random = new Random();int counter = 0;while (counter < 3) { //looping while 3 distinct cells are not set to true&nbsp; &nbsp; int rRow = random.nextInt(rows);&nbsp; &nbsp; int rCol = random.nextInt(cols);&nbsp; &nbsp; if (!mineLocations[rRow][rCol]) {&nbsp; &nbsp; &nbsp; &nbsp; mineLocations[rRow][rCol] = true;&nbsp; &nbsp; &nbsp; &nbsp; counter++; //increasing the counter only when a new cell is set to true&nbsp; &nbsp; }}逻辑很简单:在每次迭代时,您都会生成一个新坐标。然后检查此坐标处的值是否仍为 false(尚未更改)。如果是,请将其设置为 true。重复N次。

慕尼黑5688855

这是一个使用随机和内联流/用于缓存的解决方案boolean mineLocations[][] = new boolean[rows][cols];int count = rows * cols;new Random().ints(3, 0, rows * cols - 1).forEach( rand -> {&nbsp; int y = rand / rows;&nbsp; int x = rand % cols;&nbsp; mineLocations[x][y] = true;});

白衣染霜花

如何创建一个单独的方法来设置初始随机采矿位置?例如:import java.util.Arrays;import java.util.Random;class Main {&nbsp; public static void main(String[] args) {&nbsp; &nbsp; int rows = 3, cols = 4;&nbsp; &nbsp; boolean mineLocations[][] = new boolean[rows][cols];&nbsp; &nbsp; System.out.println(Arrays.deepToString(mineLocations));&nbsp; &nbsp; placeMines(3, mineLocations);&nbsp; &nbsp; System.out.println(Arrays.deepToString(mineLocations));&nbsp; }&nbsp; private static void placeMines(int numMines, boolean mineLocations[][]) {&nbsp; &nbsp; int n = mineLocations.length;&nbsp; &nbsp; int m = mineLocations[0].length;&nbsp; &nbsp; if (numMines > n * m) {&nbsp; &nbsp; &nbsp; System.err.println("Can't place more mines than slots avalaible on the grid!");&nbsp; &nbsp; &nbsp; return;&nbsp; &nbsp; }&nbsp; &nbsp; int minesPlaced = 0;&nbsp; &nbsp; while (minesPlaced != numMines) {&nbsp; &nbsp; &nbsp; int randomRow = new Random().nextInt(n);&nbsp; &nbsp; &nbsp; int randomCol = new Random().nextInt(m);&nbsp; &nbsp; &nbsp; if (!mineLocations[randomRow][randomCol]) {&nbsp; &nbsp; &nbsp; &nbsp; mineLocations[randomRow][randomCol] = true;&nbsp; &nbsp; &nbsp; &nbsp; minesPlaced++;&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; return;&nbsp; }}输出示例:[[false, false, false, false], [false,false, false, false], [false, false, false, false]][[false, false, false, true], [false, true, false, false], [false, true, false, false]]
随时随地看视频慕课网APP

相关分类

Java
我要回答