0

I am using this method with the intentions of finding the most common element in an array. It works most of the time but for some reason it doesn't always work. I would also like it to be able to store if there are 2 numbers tied for most common but I am unsure how to do so.

This picture shows the issue

Here is the code for the method: (The variable size is the size of the array)

public static int mostCommon(int size) {

        int mostCommon = 0, mostCommonCount = 0, currentCount = 0;

        for (int i = 1; i < size; i++) {

            if (array[i - 1] == array[i]) {
                currentCount++;

                if (currentCount > mostCommonCount) {
                    mostCommonCount = currentCount;
                    mostCommon = array[i];
                }
            }
            else 
                currentCount = 0;

        }

        return mostCommon;
    }

This code is in the main and prints out the most common element:

if (mostCommon(size) == 0)
            System.out.println("\nAll Elements In Your Array Occur Equally");
        else 
            System.out.println("\nThe Most Common Element In Your Array Is: " + mostCommon(size));

I would really appreciate the help. Thanks!

lospejos
  • 1,976
  • 3
  • 19
  • 35
EthanO
  • 3
  • 1
  • 1
    Post text, not pictures. – Tom Jan 11 '17 at 21:17
  • The problem might be that you only check elements against the previous one with `array[i - 1] == array[i]` –  Jan 11 '17 at 21:19
  • 3
    Your code assumes that the array is sorted, which it looks like it is not when your `mostCommon` method is run. – nickb Jan 11 '17 at 21:19
  • 1
    Possible duplicate of [Find the most popular element in int\[\] array](http://stackoverflow.com/questions/8545590/find-the-most-popular-element-in-int-array) – Keiwan Jan 11 '17 at 21:19
  • Will it work if i sort it? @nickb – EthanO Jan 11 '17 at 21:20
  • Try it and let us know ;) – nickb Jan 11 '17 at 21:20
  • It did fix the issue but how would I make it store multiple most common numbers? @nickb – EthanO Jan 11 '17 at 21:22
  • Iterate over the array and keep track of the count for each element in a `map`. – Keiwan Jan 11 '17 at 21:25
  • @Keiwan Could I use an ArrayList? – EthanO Jan 11 '17 at 21:26
  • I'm not sure how that should work. The point of using a `map` is that it stores both the numbers and their occurrences. So you'd need a `HashMap`. Here's a reference for the [HashMap](https://docs.oracle.com/javase/8/docs/api/java/util/HashMap.html) – Keiwan Jan 11 '17 at 21:32
  • Another suitable dupe: [find the frequency of elements in a java array](//stackoverflow.com/q/12207483) – Tom Jan 11 '17 at 21:33

2 Answers2

0

Guessing this is irrelevant now but thought I would answer anyway.

I don't fully understand why you would pass the size of the array in but not the array itself, anyway, I have a solution, slightly modified from your method signature but if it is still needed then it can be modified to suit your exact situation.

public static Set<Integer> mostCommon()
    {
        int[] array = new int[] {1,2,3,4,5,5,4,3,4};
        Map<Integer, Integer> counts = new HashMap<Integer,Integer>();

        Set<Integer> highestCount = new TreeSet<Integer>();

        //loop through the array to count common values
        for(int numInArray : array)
        {
            //if number in array already been seen
            if(counts.containsKey(numInArray))
            {
                counts.put(numInArray, counts.get(numInArray)+1);
            }
            //else set it at one
            else
            {
                counts.put(numInArray, 1);
            }
        }   


        //loop through map to count highest occurences
        int maxValue = 0;
        int maxKey = 0;
        for(Integer mapKey : counts.keySet())
        {
            int value = counts.get(mapKey);
            //if value is greater than maxValue then set maxVale=value, also clear highestCount as they are lower now
            if(value > maxValue)
            {
                highestCount.clear();
                maxValue = value;
                maxKey = mapKey;                
            }
            //if value is the same as maxValue then store it in list, this will allow us to get two of the same max occurences
            else if(value == maxValue)
            {

                highestCount.add(mapKey);
            }
        }
        highestCount.add(maxKey);

        System.out.println("counts " + counts);
        System.out.println("final answer " + highestCount);

        return highestCount;
    }

I have tested various values in the array and it seems to work for all I tried.

This is by no means the most efficient method it is just a solution that works.

edit: Seen your other question and the code you posted that was this method and yours works much better than this answer

johnthomsonn
  • 35
  • 11
0

You can get logic by this solution and language use to solve this problem is SWIFT 4.2

var arrColor = ["red","green","blue","green","red","green","blue","green","red","green","blue","green","blue","green","red","green","blue","blue","green","red","green","blue","blue","blue","blue","blue"]

func mostCommonArray(array:[String])->[String]{

    var commonArr = [String]()
    var dictColor = [String:Int]()

    for color in array{
        if let count = dictColor[color]{
            dictColor[color] = count + 1
        }
        else{
            dictColor[color] = 1
        }
    }
        let highestValue = dictColor.values.max()

        for (color,count) in dictColor{
            if dictColor[color] == highestValue{
                commonArr.append(color)
            }

        }


    return commonArr
}
Ankur Purwar
  • 275
  • 2
  • 9