[英]How can I put a certain amount of integers in random locations in a 2d array?
[英]Filling 2D char array with fixed amount of treasures in random locations
所以,现在我有一个2D数组,它根据用户输入(行和列)打印游戏场。 它用'.'
填充数组'.'
字符 我现在需要的,就是用第三用户输入amountTreasure
注视在地图上的宝物的数量。
我如何遍历这个2D数组并将3个宝藏放置在随机位置。 有趣的是,我需要防止计算机多次随机选择同一位置。
我现在有此代码。
public static char[][] createMatrix(int n, int m, int amountTreasure) {
Random rand = new Random();
char[][] matrix = new char[n][m];
for (char[] matrixList : matrix) {
Arrays.fill(matrixList, '.');
}
for (int v = 0; v < matrix.length; v++) { //Loop through matrix
for (int b = 0; b < matrix[v].length; b++) {
continue;
}
}
return matrix;
}
我尝试了类似的东西
matrix[v][b] = (char) rand.nextInt('X')
但它不起作用。 我对Java真的很陌生,不知道该怎么做。
与其遍历整个数组,不如计算随机位置并将宝藏放在那里。
for(int tresasure = 0; treasure < amountTreasure; treasure++) {
int x, y;
do {
x = random.nextInt(matrix.length);
y = random.nextInt(matrix[x].length);
} while(matrix[x][y] == 'X');
matrix[x][y] = 'X';
}
而不是遍历数组,而是让您的Random
返回宝藏应该去的坐标。 然后,您只需要检查是否偶然生成了相同的坐标即可。
Random random = new Random();
for (int i = 0; i < amountTreasure; i++) {
int treasureX, treasureY;
do {
treasureX = random.nextInt(n);
treasureY = random.nextInt(m);
} while (matrix[treasureX][treasureY] == 'X');
matrix[treasureX][treasureY] = 'X';
}
这是通过使用HashSet
防止重复的一种方法。 它不会遍历矩阵以选择随机位置。
这是代码片段:
public static char[][] createMatrix(int n, int m, int amountTreasure) {
Random rand = new Random();
char[][] matrix = new char[n][m];
for (char[] matrixList : matrix) {
Arrays.fill(matrixList, '.');
}
Set<String> hashSet = new HashSet<>();
/* Select At Random */
for(int iter = 0; iter < amountTreasure; iter++) {
String trs = null;
int randRow = -1;
int randCol = -1;
/* Generate New Random */
while(!hashSet.contains(trs) && trs == null) {
randRow = rand.nextInt(n);
randCol = rand.nextInt(m);
trs = new String(String.valueOf(n) + "," + String.valueOf(m));
}
/* Add In HashSet */
hashSet.add(trs);
matrix[randRow][randCol] = 'X';
}
/* Return Matrix */
return matrix;
}
输出:
. . . .
. . X .
X . X .
. . . .
您可以浏览2D数组,并将“空”单元格位置保存在另一个列表中,然后从中随机选择。 这样一来,您就无法多次选择一个单元格。
如何保存单元格位置? 您可以为单元格添加额外的类:
class Cell {
int x, y;
public Cell(int x, y) {
this.x = x;
this.y = y;
}
}
然后制作单元格的ArrayList:
List<Cell> emptyCells = new ArrayList<Cell>();
查看您的2D数组并在其中添加空单元格:
for (int v = 0; v < matrix.length; v++) { //Loop through matrix
for (int b = 0; b < matrix[v].length; b++) {
if(matrix[v][b] == '.') emptyCells.add(new Cell(v, b));
}
}
现在,您可以从中随机选择。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.