Home > Back-end >  How would you iterate through a 2D ragged array by going down through columns?
How would you iterate through a 2D ragged array by going down through columns?

Time:12-03

I would like my array to from index to index like thisfor example: (0,0), (1,0), (2,0) etc. I've tried what seems like it should be the right way, but my loops stop after the first column and I get an index out of bounds exception.

Here's what I did:

int[][] array2d = 
            {
                {4,5, 3,8},
                {8,3,99,6},
                {5,7, 9,1}
                
            }; 
int currentRow = 0;
        for (int currentColumn = 0; currentColumn < (array2d[currentRow].length); currentColumn  ) 
        { 
            for(currentRow = 0; currentRow < array2d.length; currentRow  ) 
            {
                System.out.println(array2d[currentRow][currentColumn]);
            }
        }

CodePudding user response:

You need to get the maximum number of columns before printing.

public static void main(String[] args) {
    int[][] array2d = {
        {4, 5, 3, 8},
        {},
        {8, 6},
        {2},
        {5, 7, 9, 1, 0}
    };
    int maxRow = array2d.length;
    int maxColumn = array2d[0].length;
    for (int r = 1; r < maxRow;   r)
        maxColumn = Math.max(maxColumn, array2d[r].length);
    for (int c = 0; c < maxColumn;   c) {
        for (int r = 0; r < maxRow;   r)
            if (c < array2d[r].length)
                System.out.print(array2d[r][c]   " ");
            else
                System.out.print("* ");
        System.out.println();
    }
}

output:

4 * 8 2 5 
5 * 6 * 7 
3 * * * 9 
8 * * * 1 
* * * * 0 

Or you can get away with it by scanning the row one more time.

public static void main(String[] args) {
    int[][] array2d = {
        {4, 5, 3, 8},
        {},
        {8, 6},
        {2},
        {5, 7, 9, 1, 0}
    };
    int rowSie = array2d.length;
    for (int c = 0; true;   c) {
        StringBuilder sb = new StringBuilder();
        boolean out = false;
        for (int r = 0; r < rowSie;   r)
            if (c < array2d[r].length) {
                sb.append(array2d[r][c]).append(" ");
                out = true;
            } else
                sb.append("* ");
        if (!out)
            break;
        System.out.println(sb);
    }
}

output:

4 * 8 2 5 
5 * 6 * 7 
3 * * * 9 
8 * * * 1 
* * * * 0 

CodePudding user response:

        int[][] array2d =
                {
                    {1,2,3,4},
                    {5,6,7,8},
                    { 9,10,11,12}
                };
        int r=array2d.length,c=array2d[0].length;
        for (int i=0;i<c;i  )
        {
            for(int j=0;j<r;j  )
            {
                System.out.print(array2d[j][i] " ");
            }
            System.out.println();
        }

You've ran the columns before the rows and because its a 2d array of length 3x4 , Its giving a indexOutOfBoundsException whilest iterating through the array.

CodePudding user response:

First, let's address a bug in your code. Consider this loop:

int i;
for (i = 0; i < 10; i  ) { /* loop body */ }

The loop runs until i < 10 evaluates to false. In this example, when the loop exits, i will have a value of 10.

Consider the inner loop in your code:

 for (currentRow = 0; currentRow < array2d.length; currentRow  ) 

When this loop exits, currentRow will be equal to array2d.length. Then, control will return to the outer loop. When it does, in the control expression currentColumn < (array2d[currentRow].length), this part array2d[currentRow] will throw an IndexOutOfBoundsException.

As you already know, here is the standard way of going through a 2D array in row by column order is like this:

  for (int row = 0; row < array2d.length; row  ) { 
      for (int column = 0; column < array2d[row].length; column   { 
        // things to do in inner loop
      }

If you wanted to process a rectangular 2D array in column order, the code might look like this:

 for (int column = 0; column < array2d[0].length; column  ) { 
    for (int row = 0; row < array2d.length; row  ) {
       // loop body
    }
 }

But, what if the array is ragged?

Start by finding the row with the maximum number of columns at the start:

  int maxColumns = 0;
  for (int i = 0; i < array.length; i  ) { 
     maxColumns = Math.max (maxColumns, array2d[i].length);
  }

Then, your code might look something like this:

  for (int column = 0; column < maxColumns; column  ) { 
     for (int row = 0; row < array2d.length; row  ) { 
        if (column < array2d[row].length) {
           // do something with array2d [row][column]
        } else { 
           // do something for the case where 
           // array2d [row] doesn't have a value in "column" 
        }
     }
  }

An alternative might be to try to trap an ArrayIndexOutOfBoundsException. However, that might be regarded as a poor programming practice.

  • Related