Generate grid with random characters - java

1

I want to create a grid that is filled randomly or with "W" or "_" and 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

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

    
asked by anonymous 15.06.2017 / 18:19

1 answer

1

This is because in this section:

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 from the previous iteration, that is, at the first iteration you add W to index 0, at the next iteration you add another character to the existing W or add 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 to set array typing from String to array 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();
        }

    }
}
    
15.06.2017 / 19:08