
Patrick B. answered 05/04/20
Math and computer tutor/teacher
You're still on the right track...
one problem is the intatlization statement:
double max = data[0][col];
It's possible that the column could not exist in the first row, leading to crash and burn.
You must initialize the max to some gross negative value which guarantees the
first available array element will become the max.
Otherwise I agree with your logic.
I moved the max value var to a private data member and provided a getter; the function now returns the INDEX of the largest element in the column. The results are correct for this test data. Both the column max
and it's index are output
I am a bit perturbed that the browser is messing up the columns in the array declaration. It's clean
as a whistle in notepad.
---------------------------------
class AngieARaggedArrays
{
public static final int MAX_COLUMNS=6;
private static double maxValue;
double GetMaxValue() { return(maxValue); }
/*********************************************
Returns the largest column value or -1
************************************************/
public static int getHighestInColumn(double[][]data, int col)
{
maxValue=-999999;
int iIndexPosOfMax=-1;
for (int rowLoop=0; rowLoop<data.length; rowLoop++)
{
if (
(col>=0) && (col<data[rowLoop].length)
)
// Then that column EXISTS in this particular row
{
if ( data[rowLoop][col]>maxValue) //the current max value has been DEFEATED!!
{ // new champion ;-)
maxValue = data[rowLoop][col];
iIndexPosOfMax = rowLoop;
}
}
}
return(iIndexPosOfMax);
}
public static void main(String args[])
{
double A[][] = { {5, 4, 3, 2, 1},
{4, 3, 2},
{1, 4, 7, 9, 3, 5},
{7, 8, 4, 1, 2},
{9, 3},
{1, 3, 3, 4, 5},
{2},
{7, 6, 5, 4}
};
AngieARaggedArrays x = new AngieARaggedArrays();
for (int columnLoop=0; columnLoop<x.MAX_COLUMNS; columnLoop++)
{
int iIndexPos = x.getHighestInColumn(A,columnLoop);
double maxValue = x.GetMaxValue();
System.out.println(" The highest value in column " + columnLoop
+ " is : " + maxValue
+ " which is at index position "+iIndexPos
);
}
}
}