java - Method for checking Mode -
i have method here, checking mode (most frequent element) in array. although there twist need account , i'm not sure how go doing this. example: if array {1,2,2,3,3,5} .. need print out 'nan' , because 2 , 3 both occur 2 times. on how add appreciated.
my code:
public double mode() { double maxvalue=0, maxcount=0; boolean flag=false; (int = 0; < data.length; ++i) { double count = 0; (int j = 0; j < data.length; ++j) { if (data[j]==(data[i])) ++count; } if (count > maxcount) { if(count>1)flag = true; maxcount = count; maxvalue = data[i]; } } if(flag) { return maxvalue; } else return 0.0; }
i suppose current code not giving out result wanted.
here's code snippet updated:
public double mode() { // sort array arrays.sort(data); double maxvalue = 0.0, maxcount = 0.0; (int = 0; < data.length; ++i) { // count number of elements same value int count = 0; int index = i; while (index < data.length) { if (data[i] == data[index]) { count++; index++; } else { break; } } if (count > maxcount) { maxcount = count; maxvalue = data[i]; } else if (count == maxcount) { maxcount = count; maxvalue = 0.0; } } return maxvalue; }
then, point call mode()
, following:
double m = mode(); system.out.println(m == 0.0 ? "nan" : m);
Comments
Post a Comment