Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterate through 2 dimensional array

I have a "connect four board" which I simulate with a 2d array (array[x][y] x=x coordinate, y = y coordinate). I have to use "System.out.println", so I have to iterate through the rows.

I need a way to iterate this way [0,0] [1,0] [2,0] [3,0] [0,1] [1,1] [2,1] etc

If i use the normal procedure:

for (int i = 0; i<array.length; i++){
     for (int j = 0; j<array[i].length; j++){
        string += array[i][j];
     } System.out.println(string)

}

it doesnt work because it iterates this way [0,0] [0,1] [0,2] [0,3] etc

The normal procedure stays in x and increments y until the end of the column, but i need to say in y and increment x until the end of the row.

like image 917
Peter111 Avatar asked Sep 12 '14 00:09

Peter111


2 Answers

Consider it as an array of arrays and this will work for sure.

int mat[][] = { {10, 20, 30, 40, 50, 60, 70, 80, 90},
                {15, 25, 35, 45},
                {27, 29, 37, 48},
                {32, 33, 39, 50, 51, 89},
              };


    for(int i=0; i<mat.length; i++) {
        for(int j=0; j<mat[i].length; j++) {
            System.out.println("Values at arr["+i+"]["+j+"] is "+mat[i][j]);
        }
    }
like image 65
Bharat Avatar answered Oct 07 '22 16:10

Bharat


Just invert the indexes' order like this:

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

because all rows has same amount of columns you can use this condition j < array[0].lengt in first for condition due to the fact you are iterating over a matrix

like image 34
jcstar Avatar answered Oct 07 '22 18:10

jcstar