java - How to find mode of an array, if one exists. If more than one mode, return NaN -
this question has answer here:
as title states, need find mode of array. however, there few stipulations this:
1) if no mode exists (i.e. each element appears once, or equal times) return double.nan
2) if more 1 mode exists (i.e. {1,2,2,3,4,5,5,6}
give 2 modes, 2 , 5) return double.nan
basically, should return element of array if mode of array, , appears @ least once more other elements. other time, should return double.nan
my current code returns mode. however, if 2 numbers appear equally, returns latter of 2 mode, not nan
. also, doesn't return nan
if no mode exists.
any appreciated.
here have far:
public double mode(){ double[] holder = new double[data.length]; double tempmax = 0, permmax = 0, location = 0, arraymode = 0; (int = 0; < data.length; ++i) { int count = 0; (int j = 0; j < data.length; ++j) { if (data[j] == data[i]) ++count; } holder[i] = count; } (int w = 0; w < holder.length; w++){ if (holder[w] > tempmax){ tempmax = holder[w]; arraymode = data[w]; } } permmax = arraymode; return permmax; }
it easy find duplicate question, e.g. here.
that being said, i'd add solution:
public double findmode(int[] inarray) { list<integer> il = intstream.of(inarray).boxed().collect(collectors.tolist()); int maxfreq = 0; double value = 0; (integer : ia){ if (collections.frequency(il, i) > maxfreq && != value){ maxfreq = collections.frequency(il, i); value = i; } else if (collections.frequency(il, i) == maxfreq && != value) { value = double.nan; } } return value; }
it turns int[]
list<integer>
, uses collections.frequency
method number of occurrences of each value.
disclaimer: there optimizations missed.
Comments
Post a Comment