2011-11-25 25 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(); 
     }