Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
193 views
in Technique[技术] by (71.8m points)

java - Finding modes an an array

Does anyone know how to find the modes in an array when there are more then one mode? I have this code that finds one mode. But I'm dealing with an array which has more than one mode, a multimodal array and I have to print each mode exactly once. Here is my code, can someone help me out? Thanks.

public static int mode(int a[])
{
    int maxValue=0, maxCount=0;

    for (int i = 0; i < a.length; ++i)
    {
        int count = 0;
        for (int j = 0; j < a.length; ++j)
        {
            if (a[j] == a[i]) ++count;
        }

        if (count > maxCount)
        {
            maxCount = count;
            maxValue = a[i];
        }
    }

    return maxCount;
}

public static Integer[] modes(int a[])
{
    List<Integer> modes = new ArrayList<Integer>();
    int maxCount=0;
    for (int i = 0; i < a.length; ++i)
    {
        int count = 0;
        for(int j = 0; j < a.length; ++j)
        {
            if (a[j] == a[i]) ++count;
        }

        if (count > maxCount)
        {
            maxCount = count;
            modes.clear();
            modes.add(a[i]);
        }
        else if (count == maxCount)
        {
            modes.add(a[i]);
        }
    }
    return modes.toArray(new Integer[modes.size()]);
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Since your elements will be between 10 and 1000, you can use a Counter array. In this Counter array, you can store the counts of the value of the a[i] element. I think you can understand this better in code:

public static List<Integer> mode(int[] a) {
    List<Integer> lstMode = new ArrayList<Integer>();
    final int MAX_RANGE = 1001;
    int[] counterArray = new int[MAX_RANGE]; //can be improved with some maths :)!
    //setting the counts for the counter array.
    for (int x : a) {
        counterArray[x]++;
    }
    //finding the max value (mode).
    int maxCount = counterArray[0];
    for(int i = 0; i < MAX_RANGE; i++) {
        if (maxCount < counterArray[i]) {
            maxCount = counterArray[i];
        }
    }
    //getting all the max values
    for(int i = 0; i < MAX_RANGE; i++) {
        if (maxCount == counterArray[i]) {
            lstMode.add(new Integer(i));
        }
    }
    return lstMode;
}

If your input will have elements outside of 1000, you can look for the Map answer (like in other posts).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...