简体   繁体   中英

Filling a 2D array with specific and random integers / chars

I have to create a 2D array that I print out, however I am struggling trying to include all the specific details. I am given the number of rows and columns via user input, then must print an array with "S" at the top left and "D" at the bottom right, filled with random "#"'s and random numbers. Numbers are randomly generated within the range of [1, 100] inclusively, while the total number of "#" cannot exceed the 1/3 of the total size of the matrix.

However, I'm rather stuck and don't know where to go on my code...

Code:

public void drawMaze(int numRows, int numCols) {

    int[][] mazeArray = new int[numRows][numCols];
    Random  random = new Random(); 

    // Starting Point
    mazeArray[0][0] = "S";
    // Destination Point
    mazeArray[numRows][numCols] = "D";

    for (int i = 0; i < mazeArray.length; i++) {
        for (int j = 0; j < mazeArray[i].length; j++) {
            mazeArray[i][j] = (int)(Math.random()*10);
        }
    }

}

Help would be appreciated!

This could be something like this:

public void drawMaze(int numRows, int numCols) {
    String[][] mazeArray = new String[numRows][numCols];
    Random random = new Random();
    for (int i = 0; i < mazeArray.length; i++) {
        for (int j = 0; j < mazeArray[i].length; j++) {
            int result = 1 + random.nextInt(200);
            if (result > 100) {
                mazeArray[i][j] = "#";
            } else {
                mazeArray[i][j] = Integer.toString(result);
            }
        }
    }
    //starting point
    mazeArray[0][0] = "S";
    //destination point
    mazeArray[numRows-1][numCols-1] = "D";
    for (int i = 0; i < mazeArray.length; i++) {
        for (int j = 0; j < mazeArray[i].length; j++) {
            System.out.print(String.format("%4s", mazeArray[i][j]));
        }
        System.out.println();
    }
}

200 is just a hardcoded value. You may make it dependent on arguments of the method.
4 in System.out.print(String.format("%4s", mazeArray[i][j])); is responsible for spacing (can be changed to another integer, of course).

You should not go for each field after another. Better way could be to fill the fields randomly and leaving 1/3 of your fields empty to be filled with #.

  • Fill complete array (mazeArray) with "#"
  • Calculate your overall fields to fill with numbers (numRows*numCols*2/3)=maxFields
  • Setup a 1-dimensional array (fieldsToFill) filled with 0 to maxFields, incrementing
  • Now choose randomly a number of the fieldsToFill and fill up this field pos in your 2-dim array mazeArray and delete that element from fieldsToFill

This way you get your maze filled more randomly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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