As the title states, I need to find the mode of an array. However, there are a few stipulations to this:
1) If no mode exists (i.e. each element appears only once, or equal times) return Double.NaN
2) If more than one mode exists (i.e. {1,2,2,3,4,5,5,6}
would give two modes, 2 and 5) return Double.NaN
Basically, it should only return an element of the array if it is definitely the mode of the array, and appears at least once more than all other elements. Any other time, it should return Double.NaN
My current code returns a mode. However, if two numbers appear equally, it returns the latter of the two as the mode, not NaN
. Also, doesn't return NaN
if no mode exists.
Any help is appreciated.
Here is what I have so far:
public double mode(){
double[] holder = new double[data.length];
double tempMax = 0, permMax = 0, location = 0, arrayMode = 0;
for (int i = 0; i < data.length; ++i) {
int count = 0;
for (int j = 0; j < data.length; ++j) {
if (data[j] == data[i])
++count;
}
holder[i] = count;
}
for (int w = 0; w < holder.length; w++){
if (holder[w] > tempMax){
tempMax = holder[w];
arrayMode = data[w];
}
}
permMax = arrayMode;
return permMax;
}