2011-11-25 43 views
0

虽然使用散列图查找最常见的值代码是做得很好,如果输入的数据集包含重复值另一方面,如果数据集没有重复值它也是做得好在这种情况下返回模式值过于:(HashMap方法使用它作为最常见的值

我想回到没有模式可用。 请帮助

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; 
    } 

我想找到的数据集最重复的值,或者如果数据集唐't包含任何重复值,那么它将返回“没有模式存在”

回答

1

getMode功能需要有返回“无模式存在”的一些手段。这意味着你将需要有一些特殊的价值来表示没有模式。您可以使用任何超出法定价值范围的价值,但我建议(我认为大多数人会同意我的观点)认为null是表示这一点的最佳值。为了返回null,您需要修改您的getMode以返回Float而不是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; 
    } 
} 
0

之前设置maxFreq和模式检查的频率大于1,

... 
float freq = entry.getValue(); 
     if (freq > 1 && freq > maxFreq) { 
      maxFreq = freq; 
      mode = entry.getKey(); 
     }