简体   繁体   English

在随机位置用固定数量的宝物填充2D字符数组

[英]Filling 2D char array with fixed amount of treasures in random locations

So, right now I have a 2D array, that prints a game field depending on user input(row and col). 所以,现在我有一个2D数组,它根据用户输入(行和列)打印游戏场。 It fill the array with '.' 它用'.'填充数组'.' chars. 字符 What I need now, is to use third user input amountTreasure to fixate the amount of treasures on the map. 我现在需要的,就是用第三用户输入amountTreasure注视在地图上的宝物的数量。

How can I loop through this 2D array and put for example 3 treasures in random locations. 我如何遍历这个2D数组并将3个宝藏放置在随机位置。 The interesting part is that I need to prevent computer to randomly select the same place more than once. 有趣的是,我需要防止计算机多次随机选择同一位置。

I have this code right now. 我现在有此代码。

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;
    }

I tried something like 我尝试了类似的东西

matrix[v][b] = (char) rand.nextInt('X')

but it does not work. 但它不起作用。 I am really new to Java and do not know how to do that. 我对Java真的很陌生,不知道该怎么做。

Instead of looping through the array, compute random locations and put the treasure there. 与其遍历整个数组,不如计算随机位置并将宝藏放在那里。

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';
}

Instead of looping through the array, have your Random return the coordinates of where a treasure should go. 而不是遍历数组,而是让您的Random返回宝藏应该去的坐标。 Then you just need to check whether by accident the same coordinates had been generated before. 然后,您只需要检查是否偶然生成了相同的坐标即可。

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';
}

Here is one way of doing it by using the HashSet to prevent duplicates. 这是通过使用HashSet防止重复的一种方法。 It does not loop through the matrix to choose the random locations. 它不会遍历矩阵以选择随机位置。

This is the code snippet: 这是代码片段:

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;
}

Output: 输出:

. . . . 
. . X . 
X . X . 
. . . .

You can look through your 2D-array and save the "empty" cells positions in another list and then choose randomly from them. 您可以浏览2D数组,并将“空”单元格位置保存在另一个列表中,然后从中随机选择。 That way you can't select one cell multiple times. 这样一来,您就无法多次选择一个单元格。

How to save cell positions? 如何保存单元格位置? You can make extra class for cells: 您可以为单元格添加额外的类:

class Cell {
      int x, y;
      public Cell(int x, y) {
             this.x = x;
             this.y = y;
      }
}

Then make ArrayList of Cells: 然后制作单元格的ArrayList:

List<Cell> emptyCells = new ArrayList<Cell>();

Look through your 2D array and add empty cells there: 查看您的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));
    }
}

And now you can randomly select from those. 现在,您可以从中随机选择。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM