Advertisement
brilliant_moves

MostFrequentNumbers.java

Apr 7th, 2015
405
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 5 1.60 KB | None | 0 0
  1. import java.util.Random;
  2. import java.util.Arrays;
  3.  
  4. public class MostFrequentNumbers {
  5.  
  6.     /* Sometimes there is more than one value that occurs most often in a random array */
  7.  
  8.     static final int N = 40;    // number of numbers in array
  9.     static final int MAX = 4 * N;   // range is zero to MAX inclusive
  10.  
  11.     static int[] counts = new int[MAX+1]; // number of occurances for each number
  12.  
  13.     public static int getMaxCount(int[] n) {
  14.     // determine the maximum occurances of any number in array
  15.         int maxCount = 0; // count of most occurances
  16.         for (int i=0; i<n.length; i++) {
  17.             counts[n[i]]++;
  18.             if (maxCount<counts[n[i]]) {
  19.                 maxCount = counts[n[i]];
  20.             } // end if
  21.         } // end for
  22.         return maxCount;
  23.     } // end getMaxCount()
  24.  
  25.     public static void printMostFrequent(int[] n) {
  26.     // print the numbers which appear most often
  27.  
  28.         int mostTimes = getMaxCount(n);
  29.         boolean[] printed = new boolean[MAX+1]; // so that numbers are only printed once
  30.  
  31.         for (int i=0; i<n.length; i++) {
  32.             if (counts[n[i]]==mostTimes && !printed[n[i]]) {
  33.                 System.out.print(n[i]+" ");
  34.                 printed[n[i]]= true; // so we don't print it again
  35.             } // end if
  36.         } // end for
  37.         System.out.println();
  38.     } // end printMostFrequent()
  39.  
  40.     public static void main(String[] args) {
  41.         Random ran = new Random();
  42.         int[] A = new int[N];
  43.  
  44.         // populate array with random numbers
  45.         for (int i=0; i<N; i++) {
  46.             A[i] = ran.nextInt(MAX+1);
  47.         } // for
  48.  
  49.         Arrays.sort(A);
  50.         System.out.println( Arrays.toString(A));
  51.  
  52.         System.out.print("Most frequently occuring number(s): ");
  53.         printMostFrequent(A);          
  54.     } // main()
  55.  
  56. } // class MostFrequentNumbers
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement