Search code examples
javaandroidhashmapmode

HashMap method in using it as a most common value


while using hashmap for finding the most common value the code is doing well if the entered data set contains repeating value on the other hand if the data set has no repeating value it is also returning mode value in that case too :(

I want to return that no mode is available . please help

    public void onMode(View Button){

    EditText inp = (EditText) findViewById(R.id.EditText01);
    float[] input = new float[uno];
    float answer = 0;
    input = points;
    answer = getMode(input);

    Float floatInput2 = new Float (answer);
    String newinput2 = floatInput2.toString();

    inp.setText("Your required Mode is "+newinput2);

}
public static float getMode(float[] values) {
      HashMap<Float,Float> freqs = new HashMap<Float,Float>();

      for (float val : values) {
        Float freq = freqs.get(val);
        freqs.put(val, (freq == null ? 1 : freq+1));
      }

      float mode = 0;
      float maxFreq = 0;

      for (Map.Entry<Float,Float> entry : freqs.entrySet()) {
        float freq = entry.getValue();
        if (freq > maxFreq) {
          maxFreq = freq;
          mode = entry.getKey();
        }
      }

      return mode;
    }

I want to find the most repetitive value in the data set or if data set don't contains any repeating value then it will return "no mode exist"


Solution

  • Your getMode function will need to have some means of returning that "no mode exists". That means you will need to have some special value to represent not having a mode. You can use any value outside of the range of legal values to be returned, but I recommend (and I think most would agree with me) that null is the best value to signify that. In order to return null, you will need to modify your getMode to return a Float rather than a float.

    public void onMode(View Button){
      EditText inp = (EditText) findViewById(R.id.EditText01);
      float[] input = new float[uno];
      input = points;
    
      Float floatInput2 = getMode(input);
      String newinput2 = floatInput2.toString();
    
      if (floatInput2 != null) {
        inp.setText("Your required Mode is "+newinput2);
      } else {
        inp.setText("No mode was found.");
      }
    }
    
    public static Float getMode(float[] values) {
      HashMap<Float,Float> freqs = new HashMap<Float,Float>();
    
      for (float val : values) {
        Float freq = freqs.get(val);
        freqs.put(val, (freq == null ? 1 : freq+1));
      }
    
      float mode = 0;
      float maxFreq = 0;
    
      for (Map.Entry<Float,Float> entry : freqs.entrySet()) {
        float freq = entry.getValue();
        if (freq > maxFreq) {
          maxFreq = freq;
          mode = entry.getKey();
        }
      }
    
      if (maxFreq > 1) {
        return mode;
      } else {
        return null;
      }
    }