Generate grid with random characters - java

Asked

Viewed 115 times

1

I intend to create a grid that is filled randomly or with "W" or "_" and I did the following:

public class Gerador_grelha {

public static void main(String[] args) {

    int row = 5;
    int col = 5;
    String[][] grid = new String[row][col];
    String AB = "_W";
    SecureRandom rnd = new SecureRandom();
    for (int i = 0; i < grid.length; i++) {
        StringBuilder sb = new StringBuilder(row);
        for (int j = 0; j < grid[i].length; j++) {
            sb.append(AB.charAt(rnd.nextInt(AB.length())));
            sb.toString();
            grid[i][j] = sb.toString();
        }
    }

    for(String[] row:grid) {
        for(String c:row) {
            System.out.print(c);
        }System.out.println();
    }

}

But in this case it would be a 5 by 5 grid I’m getting one like this:

WW_W_WW_W_W_W__
_____W__W___W__
__W_WW_WWW_WWW_
__W_WW_WW__WW_W
______________W

Which is clearly not 5 by 5. Can anyone help solve the problem?

1 answer

1


This is why in this passage:

StringBuilder sb = new StringBuilder(row);
for (int j = 0; j < grid[i].length; j++) {
    sb.append(AB.charAt(rnd.nextInt(AB.length())));
    sb.toString();
    grid[i][j] = sb.toString();

}

You are always concatenating the leftover of the previous iteration, that is, in the first iteration you add W to index 0, in the next iteration you add another character to W existing or added WW to index 2, so on. At the end you will have a string in each index, not necessarily a character.

to adjust you can simply change the excerpt I mentioned by this:

for (int j = 0; j < grid[i].length; j++) {
    Character c = AB.charAt(rnd.nextInt(AB.length()));
    grid[i][j] = c.toString();
}

Now a better way to write this code would be by adjusting the typing of the array of String for array of char:

public class Gerador_grelha {

    public static void main(String[] args) {

        int row = 5;
        int col = 5;
        String AB = "_W";

        char[][] grid = new char[row][col];
        SecureRandom rnd = new SecureRandom();

        for (int i = 0; i < grid.length; i++) {
            for (int j = 0; j < grid[i].length; j++) {
                char c = AB.charAt(rnd.nextInt(AB.length()));
                grid[i][j] = c;
            }
        }

        for (char[] r : grid) {
            for (char c : r) {
                System.out.print(c);
            }
            System.out.println();
        }

    }
}
  • thank you, indeed the mistake was that.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.