Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print 2D array with a single for loop

How to print a 2d array in java using a single for-loop?

I tried to search answers but only found solutions using multiple loops.

Example array:

[
    [1, 2, 3],
    [4, 5],
    [6, 7, 8],
    [9]
]

Example output (the exact format does not matter):

1, 2, 3, 4, 5, 6, 7, 8, 9

With a single for-loop, not a nested loop.


So not something like this:

for (int i = 0; i < array.length; i++) {
    for (int j = 0; j < array[i].length; j++) {
        System.out.print(array[i][j] + " ");
    }
}
like image 952
Uzair Ahmed Avatar asked Dec 14 '22 09:12

Uzair Ahmed


1 Answers

The principle to read a 2D array with a single loop : one [H,W] 2D matrix could be computed as a 1D matrix of HxW length.

On this basis a solution could be:

int[][] arr = {{1, 2, 3}, {4, 5, 8}, {5, 6, 7}};
int hight = arr.length;
int width = arr[0].length;
for (int i = 0; i < width * hight; i++) {
    int li = i / hight;
    int col = i % hight;
    System.out.print(arr[li][col]);
    if (col == width - 1) System.out.println();
}

Output:

123
458
567
like image 131
kevin ternet Avatar answered Jan 02 '23 01:01

kevin ternet