Write a mode method in Java to find the most frequently occurring element in an array

前端 未结 14 2435
清酒与你
清酒与你 2020-11-29 07:17

The question goes:

Write a method called mode that returns the most frequently occurring element of an array of integers. Assume that the array has at le

相关标签:
14条回答
  • 2020-11-29 07:18

    import java.util.HashMap;

    public class SmallestHighestRepeatedNumber { static int arr[] = { 9, 4, 5, 9, 2, 9, 1, 2, 8, 1, 1, 7, 7 };

    public static void main(String[] args) {
        int mode = mode(arr);
        System.out.println(mode);
    }
    
    public static int mode(int[] array) {
        HashMap<Integer, Integer> hm = new HashMap<Integer, Integer>();
        int max = 1;
        int temp = 0;
    
        for (int i = 0; i < array.length; i++) {
    
            if (hm.get(array[i]) != null) {
    
                int count = hm.get(array[i]);
                count++;
                hm.put(array[i], count);
    
                if (count > max || temp > array[i] && count == max) {
                    temp = array[i];
                    max = count;
                }
            } else
                hm.put(array[i], 1);
        }
        return temp;
    }
    

    }

    0 讨论(0)
  • 2020-11-29 07:20

    You should be able to do this in N operations, meaning in just one pass, O(n) time.

    Use a map or int[] (if the problem is only for ints) to increment the counters, and also use a variable that keeps the key which has the max count seen. Everytime you increment a counter, ask what the value is and compare it to the key you used last, if the value is bigger update the key.

    public class Mode {
    public static int mode(final int[] n) {
        int maxKey = 0;
        int maxCounts = 0;
    
        int[] counts = new int[n.length];
    
        for (int i=0; i < n.length; i++) {
            counts[n[i]]++;
            if (maxCounts < counts[n[i]]) {
                maxCounts = counts[n[i]];
                maxKey = n[i];
            }
        }
        return maxKey;
    }
    
    public static void main(String[] args) {
        int[] n = new int[] { 3,7,4,1,3,8,9,3,7,1 };
        System.out.println(mode(n));
    }
    }
    
    0 讨论(0)
  • 2020-11-29 07:21

    Here, I have coded using single loop. We are getting mode from a[j-1] because localCount was recently updated when j was j-1. Also N is size of the array & counts are initialized to 0.

            //After sorting the array 
            i = 0,j=0;
            while(i!=N && j!=N){
                if(ar[i] == ar[j]){
                    localCount++;
                    j++;
                }
                else{
                    i++;
                    localCount = 0;
                }
                if(localCount > globalCount){
                    globalCount = localCount;
                    mode = ar[j-1]; 
                }
            }
    
    0 讨论(0)
  • 2020-11-29 07:22

    I have recently made a program that computes a few different stats, including mode. While the coding may be rudimentary, it works for any array of ints, and could be modified to be doubles, floats, etc. The modification to the array is based on deleting indexes in the array that are not the final mode value(s). This allows you to show all modes (if there are multiple) as well as have the amount of occurrences (last item in modes array). The code below is the getMode method as well as the deleteValueIndex method needed to run this code

    import java.io.File;
    import java.util.Scanner;
    import java.io.PrintStream;
    
    public static int[] getMode(final int[] array) {           
      int[] numOfVals = new int[array.length];
      int[] valsList = new int[array.length];
    
      //initialize the numOfVals and valsList
    
      for(int ix = 0; ix < array.length; ix++) {
         valsList[ix] = array[ix];
      }
    
      for(int ix = 0; ix < numOfVals.length; ix++) {
         numOfVals[ix] = 1;
      }
    
      //freq table of items in valsList
    
      for(int ix = 0; ix < valsList.length - 1; ix++) {
         for(int ix2 = ix + 1; ix2 < valsList.length; ix2++) {
            if(valsList[ix2] == valsList[ix]) {
               numOfVals[ix] += 1;
            }
         }
      }
    
      //deletes index from valsList and numOfVals if a duplicate is found in valsList
    
      for(int ix = 0; ix < valsList.length - 1; ix++) {   
         for(int ix2 = ix + 1; ix2 < valsList.length; ix2++) {
            if(valsList[ix2] == valsList[ix]) {
               valsList = deleteValIndex(valsList, ix2);
               numOfVals = deleteValIndex(numOfVals, ix2);
            }
         }
      }
    
      //finds the highest occurence in numOfVals and sets it to most
    
      int most = 0;
    
      for(int ix = 0; ix < valsList.length; ix++) {
         if(numOfVals[ix] > most) {
            most = numOfVals[ix];
         }
      }
    
      //deletes index from valsList and numOfVals if corresponding index in numOfVals is less than most
    
      for(int ix = 0; ix < numOfVals.length; ix++) {
         if(numOfVals[ix] < most) {
            valsList = deleteValIndex(valsList, ix);
            numOfVals = deleteValIndex(numOfVals, ix);
            ix--;
         }
      }
    
      //sets modes equal to valsList, with the last index being most(the highest occurence)
    
      int[] modes = new int[valsList.length + 1];
    
      for(int ix = 0; ix < valsList.length; ix++) {
         modes[ix] = valsList[ix];
      }
    
      modes[modes.length - 1] = most;
    
      return modes;
    
    }
    
    public static int[] deleteValIndex(int[] array, final int index) {   
      int[] temp = new int[array.length - 1];
      int tempix = 0;
    
      //checks if index is in array
    
      if(index >= array.length) {
         System.out.println("I'm sorry, there are not that many items in this list.");
         return array;
      }
    
      //deletes index if in array
    
      for(int ix = 0; ix < array.length; ix++) {
         if(ix != index) {
            temp[tempix] = array[ix];
            tempix++;
         }
      }
      return temp;
    }
    
    0 讨论(0)
  • 2020-11-29 07:24

    I would use this code. It includes an instancesOf function, and it runs through each number.

    public class MathFunctions {
    
    public static int mode(final int[] n) {
        int maxKey = 0;
        int maxCounts = 0;
    
        for (int i : n) {
            if (instancesOf(i, n) > maxCounts) {
                maxCounts = instancesOf(i, n);
                maxKey = i;
            }
        }
    
        return maxKey;
    }
    
    public static int instancesOf(int n, int[] Array) {
        int occurences = 0;
        for (int j : Array) {
            occurences += j == n ? 1 : 0;
        }
        return occurences;
    }
    
    public static void main (String[] args) {
        //TODO Auto-generated method stub
        System.out.println(mode(new int[] {100,200,2,300,300,300,500}));
    }
    }
    

    I noticed that the code Gubatron posted doesn't work on my computer; it gave me an ArrayIndexOutOfBoundsException.

    0 讨论(0)
  • 2020-11-29 07:26

    I know that this question is from a while ago, but I wanted to add an answer that I believe expands upon the original question. The addendum to this question was to write the mode method without relying upon a preset range (in this case, 0 through 100). I have written a version for mode that uses the range of values in the original array to generate the count array.

    public static int mode(int[] list) {
    
        //Initialize max and min value variable as first value of list
        int maxValue = list[0]; 
        int minValue = list[0];
    
        //Finds maximum and minimum values in list
        for (int i = 1; i < list.length; i++) {
            if (list[i] > maxValue) {
                maxValue = list[i];
            }
    
            if (list[i] < minValue) {
                minValue = list[i];
            }
        }
    
        //Initialize count array with (maxValue - minValue + 1) elements  
        int[] count = new int[maxValue - minValue + 1];
    
        //Tally counts of values from list, store in array count
        for (int i = 0; i < list.length; i++) {
            count[list[i] - minValue]++; //Increment counter index for current value of list[i] - minValue
        }
    
        //Find max value in count array
        int max = count[0]; //Initialize max variable as first value of count
    
        for (int i = 1; i < count.length; i++) {
            if (count[i] > max) {
                max = count[i];
            }
        }
    
        //Find first instance where max occurs in count array
        for (int i = 0; i < count.length; i++) {
            if (count[i] == max) {
                return i + minValue; //Returns index of count adjusted for min/max list values - this is the mode value in list
            }
        }
        return -1; //Only here to force compilation, never actually used
    }
    
    0 讨论(0)
提交回复
热议问题