Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...