samedi 20 février 2016

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). 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.

How can I loop through this 2D array and put for example 3 treasures in random locations. 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.




Aucun commentaire:

Enregistrer un commentaire