【问题标题】:HashMap method in using it as a most common valueHashMap 方法中使用它作为最常见的值
【发布时间】:2012-01-06 01:46:28
【问题描述】:

在使用 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;
    }

我想在数据集中找到重复次数最多的值,或者如果数据集中不包含任何重复值,那么它将返回“不存在模式”

【问题讨论】:

    标签: java android hashmap mode


    【解决方案1】:

    在设置 maxFreq 和 mode 之前检查 freq 是否大于 1,

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

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-12-24
        • 2014-01-06
        • 2011-09-02
        • 1970-01-01
        • 1970-01-01
        • 2020-03-03
        • 1970-01-01
        • 2011-10-07
        相关资源
        最近更新 更多