How to combine two FORs into one

It may be stupid, but I want to know if this is possible, let's start with a 5x5 matrix

int[][] x = new int[5][5];      
Random rg = new Random();

now you can 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 it 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 does not work: (

+3
source share
7 answers

You need to compute the row and column from one index, and then:

for(int i = 0; i < 5 * 5; i++)
{
   int row = i / 5;
   int column = i % 5;
   x[row][column] = rg.nextInt();
}

Using / and% is classic, here: when you iterate over matrix indices, division is used to determine which row you are on. The rest (%) is a column.

This great ASCII art shows how 1-dimensional indexes are arranged in a 2D matrix:

 0  1  2  3  4
 5  6  7  8  9
10 11 12 13 14
15 16 17 18 19
20 21 22 23 24

, , 5, , 0.

+25

. . , . ( divide mod ALU)

+8

:

int i,j;
for (i=0,j=0; i<5 && j<5; i = (i==4 ? 0 : i+1), j = (i==4 ? j+1 : j))
{
   x[i][j] = rg.nextInt();
}

.

+2

.

Suns HotSpot 64 server jvm Linux , , [ * ]. , infact , , , , .

, IBMs jdk 1.5 32 Windows, 10 .

, jvm, IBM RAD, , eclipse 3.4

, , "enterpriseisy" jvm , .

0
source

nested loops will be very fast once the hotspot compiler starts them several times. see this great article for an explanation .

0
source

The shortest solution

int i = 0,j=0;
 for(;j<5;j+=i==4?1:0,i++){
    if(i==5)
       i=0;
    x[j][i] = rg.nextInt();

  }
0
source
 int q = 5, r= 5;
 int [][] x = new int [q][r]

for(int i = 0, i < q * r, i++)
{
    int xaxis = i / q;
    int yaxis = i % r;

    x[xaxis][yaxis] = rg.nextInt();
}

Although I don’t know why you want ... you will still have the same number of iterations and this IMHO is harder to read and requires more mathematical calculations to run, so it is probably slower if you profile it

-1
source

Source: https://habr.com/ru/post/1709078/


All Articles