3 回答
TA贡献1779条经验 获得超6个赞
下面是一个如何执行此操作的示例:
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
int rRow = random.nextInt(rows);
int rCol = random.nextInt(cols);
if (!mineLocations[rRow][rCol]) {
mineLocations[rRow][rCol] = true;
counter++; //increasing the counter only when a new cell is set to true
}
}
逻辑很简单:在每次迭代时,您都会生成一个新坐标。然后检查此坐标处的值是否仍为 false(尚未更改)。如果是,请将其设置为 true。
重复N次。
TA贡献1848条经验 获得超2个赞
这是一个使用随机和内联流/用于缓存的解决方案
boolean mineLocations[][] = new boolean[rows][cols];
int count = rows * cols;
new Random().ints(3, 0, rows * cols - 1).forEach( rand -> {
int y = rand / rows;
int x = rand % cols;
mineLocations[x][y] = true;
});
TA贡献1796条经验 获得超10个赞
如何创建一个单独的方法来设置初始随机采矿位置?
例如:
import java.util.Arrays;
import java.util.Random;
class Main {
public static void main(String[] args) {
int rows = 3, cols = 4;
boolean mineLocations[][] = new boolean[rows][cols];
System.out.println(Arrays.deepToString(mineLocations));
placeMines(3, mineLocations);
System.out.println(Arrays.deepToString(mineLocations));
}
private static void placeMines(int numMines, boolean mineLocations[][]) {
int n = mineLocations.length;
int m = mineLocations[0].length;
if (numMines > n * m) {
System.err.println("Can't place more mines than slots avalaible on the grid!");
return;
}
int minesPlaced = 0;
while (minesPlaced != numMines) {
int randomRow = new Random().nextInt(n);
int randomCol = new Random().nextInt(m);
if (!mineLocations[randomRow][randomCol]) {
mineLocations[randomRow][randomCol] = true;
minesPlaced++;
}
}
return;
}
}
输出示例:
[[false, false, false, false], [false,false, false, false], [false, false, false, false]]
[[false, false, false, true], [false, true, false, false], [false, true, false, false]]
添加回答
举报