# 2D Array transposition

• 12-02-2011, 09:39 AM
Rederich
2D Array transposition
Hey all, im getting an "array index out of bounds error" but dont see why i would be getting it...

here is the code:
Code:

``` int[][] transpose(int [][] a) {         int n = a.length;         int m = a[n-1].length;         int [][]b = new int [m][n];         for(int i=0;i<n;i++){                for(int j=0;i<m;j++) {                           b[j][i]=a[i][j]; <-- this is where im getting the error at, although i dont see how im going out of bounds..:frusty:                               }         }         return b;     }```
I would greatly appreciate it if someone could help me out, thank you.
• 12-02-2011, 11:49 AM
JosAH
Re: 2D Array transposition
Is array 'a' a 'ragged' array? e.g. int[][] a= { { 1, 2 }, { 3, 4, 5 }}; in this array not all rows have the same size and it ruins your transpose( ... ) method.

kind regards,

Jos
• 12-02-2011, 07:04 PM
Rederich
Re: 2D Array transposition
We are to assume that all the rows are of equal length. Sorry, i should have mentioned that. Just to keep things simple ive been assigning the parameter to be a square matrix, but im still getting the error.
• 12-02-2011, 07:11 PM
Rewry
Re: 2D Array transposition
i think the condition of the second for loop is incorrect...take a look
• 12-02-2011, 07:13 PM
JosAH
Re: 2D Array transposition
Quote:

Originally Posted by Rederich
We are to assume that all the rows are of equal length. Sorry, i should have mentioned that. Just to keep things simple ive been assigning the parameter to be a square matrix, but im still getting the error.

I only see your mistake now: check the conditional expression in your inner loop; it should be j instead of i ...

kind regards,

Jos
• 12-02-2011, 07:43 PM
Rederich
Re: 2D Array transposition
Thanks for pointing that out. I should really pay attention to detail...XD.
• 12-02-2011, 09:03 PM
JosAH
Re: 2D Array transposition
Quote:

Originally Posted by Rederich
Thanks for pointing that out. I should really pay attention to detail...XD.

You're welcome of course; your nasty little mistake was hard to spot; a tip: add the tag [code] above your Java code and put a [/code] tag just below it; I did the same in your original post to make the code more readable.

kind regards.
• 12-02-2011, 09:13 PM
Rewry
Re: 2D Array transposition
No prob, glad to help =)