This might be stupid, but I’m want to know if it’s possible, lets start with 5×5 a matrix
int[][] x = new int[5][5];
Random rg = new Random();
now let’s fill it with Pseudo Random information
for(int i=0;i<5;i++){
for(int j =0; j<5;j++){
x[i][j] = rg.nextInt();
}
}
but how can I do this right with one Single for?
for(int i=0, j=0; i<5; (j==5?i++, j=0:j++){
x[i][j] = rg.nextInt();
}
this is not working 🙁
You need to compute the row and column from a single index, then:
The use of / and % is classic, here: as you iterate over the indices of the matrix, the division is used to figure out which row you’re on. The remainder (%) is then the column.
This gorgeous ASCII art shows how the 1-dimensional indices are located in the 2D matrix:
It should be clear that for any value in the first row, that value divided by 5 is the row index itself, i.e. they’re all 0.