Reputation: 238
I have a 2-dimensional array which has rows of different lengths. I want to write a method that returns a new array which consists of the maximum elements of columns. If this was a simple n x m array, it would be easy but since the rows are variable length, I can't come up with a solution to account for the different number of elements in columns.
For example, the array looks like this:
int[][] test = { { 0, 1, 4, 5, 6, 8 },
{ 4, 5, 8, 3, 9 },
{ 3, 6, 2 }
};
The expected result would then be:
int[] result = {4, 6, 8, 5, 9, 8};
I have got the code to find the maximum elements of rows but I'm out of ideas how to adjust it for the columns.
int[] result = new int[m.length];
for (int x = 0; x < m.length; x++) {
result[x] = 0;
for (int y = 0; y < m[x].length; y++) {
if (result[x] < m[x][y]) {
result[x] = m[x][y];
}
}
}
Any help would be appreciated
EDIT: I realized now that the first thing to do is finding the row with maximum number of elements since that defines the size of the new array. From there.. should probably take the elements of a row and compare them with the elements at the same position in the new array. And do this with every row. Then it doesn't matter how short the other rows are. Am I on the right way?
Upvotes: 3
Views: 6000
Reputation: 93090
First you want to find the length of the largest row.
Then, similarly to your algorithm, but you want to make sure not to get out of bounds exception. That's it:
int maxcol = 0;
for(int i = 0; i < test.length; i++)
if(test[i].length > maxcol)
maxcol = test[i].length;
int[] result = new int[maxcol];
for (int j = 0; j < maxcol; j++)
for (int i = 0; i < test.length; i++)
if (test[i].length > j && result[j] < test[i][j])
result[j] = test[i][j];
Upvotes: 2