Reputation: 31
So I'm trying to come up with this method that will display the index of the maximum number in the 2D array. I was able to do it for a single D array, but I'm having trouble doing it for the 2D.
public static int findMaximumValue(int[ ][ ] a)
{
int maxVal = a [0][0];
int i = 0;
for(i = 0; i < a.length; i++)
{
for(int j = 0; j < a[0].length; j++)
{
if(a[i][j] > maxVal)
{
maxVal = a[i][j];
}
}
}
return(maxVal);
}
2D ARRAY
public static int [][] findMaximumIndex(int[ ][ ] a)
{
int maxVal = a[0][0];
int [][] maxIndex = new int [1][2];
int row = 0, col = 0;
for(row = 0; row < a.length; row++)
{
for(col = 0; col < a[row].length; col++)
{
if(a[row][col] > maxVal)
{
maxVal = a[row][col];
maxIndex [1] [2] = a[row][col];
}
}
}
return(maxIndex);
}
Upvotes: 1
Views: 6219
Reputation: 5457
First, you are returning a 2d int array when you want to return the index of the maxValue which will be a row index and a column index. Perhaps you want to return an array of size 2 to represent this? more info would be helpful. Second, I'm not sure what your doing with the maxIndex 2d array. Each time you iterate through the 2d array, just comepare the maxvalue to the current element. havent got an IDE near to debug but should go something like this:
public static int[] findMaximumIndex(int[ ][ ] a)
{
int maxVal = -99999
int[] answerArray = new int[2];
for(int row = 0; row < a.length; row++)
{
for(int col = 0; col < a[row].length; col++)
{
if(a[row][col] > maxVal)
{
maxVal = a[row][col];
answerArray[0] = row;
answerArray[1] = col;
}
}
}
return answerArray;
}
here answerArray[0] will have the row index for the max element and answerArray[1] will have the column index for the max element
Upvotes: 1