有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java计算模式

我正在尝试编写一个方法来计算一组数据的模式并返回它。如果没有模式或有多个模式(例如:If4&;2返回的次数最多),我希望函数返回Double。楠。我能够获得模式,但如果有多个模式,我的代码返回双NaN时遇到问题

这是我的密码

public double mode() {

    if (data == null) {
        double mode;
        mode = Double.NaN;
        return mode; // returns no value if array is null
    }

    double mode = 0;
    double modeCounter = 0;

    for (int c = 0; c < data.length; ++c) {
        int count = 0;
        for (int i = 0; i < data.length; ++i) {
            if (data[i] == data[i])
                ++count;
        }
        if (count > modeCounter) {
            modeCounter = count;
            mode = data[c];
        }
    }
    if (!(modeCounter > 1)) {
        return Double.NaN;
    }

    return mode;

}

共 (1) 个答案

  1. # 1 楼答案

    我假设您正在使用Java

    我们可以通过简单地创建一个Map来找到模式(以及您对返回Double.NaN的限制),其中键是各个数据点,值是它们在数据数组中的对应计数

    Stream对于编写可读且简洁的代码非常有用

    如果您有数组/数组列表中每个成员的计数,您只需使用此计数即可根据您的需求得出结论

    请参阅实现上述说明的以下代码:

    public static Double mode(List<Double> data) {
        if (data.isEmpty()) {
            // returning NaN if the input arraylist is empty 
            return Double.NaN;
        }
    
        Map<Double, Integer> count = new HashMap<>();
        data.forEach(
                i -> {
                    count.putIfAbsent(i, 1);
                    count.put(i, count.get(i) + 1);
                }
        );
        int maxCount = count.values().stream().max(Integer::compare).get(); // this assumes that the data is not empty
        if (count.values().stream().filter(i -> i == maxCount).count() > 1) {
            // more than one mode present
            return Double.NaN;
        }
    
        // here we'll be sure that only one mode exists
        return count
                .entrySet()
                .stream()
                .filter(e -> e.getValue() == maxCount)
                .findFirst() // as we've only one mode
                .get()
                .getKey();
    }