It is supposed to calculate the mode in Java, NOT using Array List, however, I can utilize
Question:
It is supposed to calculate the mode in Java, NOT using Array List, however, I can utilize another method if needed. If the input is 6 1 3 2 4 6 5 then the Mode: [1.000 2.000 3.000 4.000 5.000 6.000] , if the input is 10 1 3 2 4 6 5 6 6 6 6 then the Mode: [6.000]. The code I currently have is outputting a repeating number 6 and 0 for the second input sample because I do not know how to fix the list size. I see where the code is failing at for the desired output, but I am not sure how to fix it.
public static double[] calculateMode(double[] numbers) {
int maxCount = 0; //To store the maximum frequency
int modeCount = 0; //To count the number of modes
double[] mode = new double[numbers.length];
for (int i = 0; i < numbers.length; ++i) {
double num = numbers[i];
int currCount = 0;
for (int j = 0; j < numbers.length; ++j) {
if (num == numbers[j]) {
currCount++;
}
}
if (currCount > maxCount) {
maxCount = currCount;
modeCount = 1;
mode[0] = num;
}
else if (currCount == maxCount) {
mode[modeCount] = num;
modeCount++;
}
}
return mode;
}
Income Tax Fundamentals 2013
ISBN: 9781285586618
31st Edition
Authors: Gerald E. Whittenburg, Martha Altus Buller, Steven L Gill