Advertisement
binibiningtinamoran

Mode

May 28th, 2019
120
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.07 KB | None | 0 0
  1. public class Mode {
  2.  
  3.     public static void main(String []args) {
  4.         int[] arr = new int[] {1,2,2,3,3,4};
  5.  
  6.         System.out.println(calcMode(arr));
  7.  
  8.     }
  9.  
  10.     private static String calcMode(int[] array)
  11.     {
  12.         int[] counts = new int[array.length];
  13.         for (int i = 0; i < array.length; i++) {
  14.             counts[array[i]]++;
  15.         }
  16.         int max = counts[0];
  17.         for (int counter = 1; counter < counts.length; counter++) {
  18.             if (counts[counter] > max) {
  19.                 max = counts[counter];
  20.             }
  21.         }
  22.  
  23.         int[] modes = new int[array.length];
  24.  
  25.         int j = 0;
  26.         for (int i = 0; i < counts.length; i++) {
  27.             if (counts[i] == max)
  28.                 modes[j++] = array[i];
  29.         }
  30.  
  31.         toString(modes);
  32.         return "";
  33.     }
  34.  
  35.     public static void toString(int[] array)
  36.     {
  37.         System.out.print("{");
  38.         for(int element: array)
  39.         {
  40.             if(element > 0)
  41.                 System.out.print(element + " ");
  42.         }
  43.         System.out.print("}");
  44.     }
  45. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement