PRCube PRCube - 1 month ago 8
Java Question

set value for random element on matrix

I'm trying to generate a 8 by 8 matrix. Each element of matrix needs to have a value of 1 except one element on each column which is set as 0, that one element is chosen by generating a random int between 0-7.

What I get when I run the code:

1 1 1 1 1 1 1 1
1 1 1 0 1 1 1 1
1 1 0 1 1 1 1 1
1 0 1 1 1 1 1 1
1 0 1 1 1 1 1 1
1 0 0 1 1 1 1 1
1 1 1 1 1 1 1 1
1 1 1 1 1 0 1 1


My matrix should look like this:

1 1 1 1 1 1 1 1
1 1 0 1 1 1 1 1
1 1 1 1 1 0 1 0
0 1 1 1 1 1 1 1
1 1 1 0 1 1 0 1
1 0 1 1 1 1 1 1
1 1 1 1 1 1 1 1
1 1 1 1 0 1 1 1


code

for (int[] row: grid)
Arrays.fill(row, 1);

for(int i=0; i<grid.length; i++) {
int j = getRandom();
grid[i][j] = 0;
}

// print matrix
for (int i = 0; i < 8; i++) {
for (int j = 0; j < 8; j++) {
System.out.format("%2s%2d%2s", " ", Main.grid[i][j], " ");
}
System.out.println();
}

Answer

In your nested loop, both initialization and nulling of cells are in the innermost loop. This will cause both to run once per cell, but nulling is only done once per column.

If we change the order that the cells are initialized in from row after row to column after column, we can move the nulling logic out to the outermost loop.

for (int c = 0; c < 8; c++) {
    for (int r = 0; r < 8; r++) {
        Main.grid[r][c] = 1;
    }

    Main.grid[getRandom()][c] = 0; // assuming your getRandom() is within range
}
Comments