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: (
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.
. . , . ( divide mod ALU)
:
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(); }
.
Suns HotSpot 64 server jvm Linux , , [ * ]. , infact , , , , .
, IBMs jdk 1.5 32 Windows, 10 .
, jvm, IBM RAD, , eclipse 3.4
, , "enterpriseisy" jvm , .
nested loops will be very fast once the hotspot compiler starts them several times. see this great article for an explanation .
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(); }
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
Source: https://habr.com/ru/post/1709078/More articles:Problem using GIcon () for google maps - google-mapsDoes Log4Net incubate? - loggingThe correct Return-Path header format is emailC #: Why is my process running on Java.exe excellent, but the window does not return ANY output? - c #Eclipse RCP: how to observe the status of cut / copy / paste commands? - eclipseWhat is a mature program? - language-designHow to find out if the application restarted after a phone call? - iphoneDivide a square into small squares - mathRegular expression to combine numbers - vimWhat is the easiest way to find a join model, given two objects when using has_many: via - ruby-on-railsAll Articles