# Working With Frequency Arrays...

• 12-18-2009, 02:32 AM
Hexbomber
Working With Frequency Arrays...
So I have a hobby project I'm working on, where I have read in 100 000 random numbers between 1 and 50.
I have stored them in a frequency array of int's, (aptly named freq[]). So basically every time I read in
the number X, I would go freq[X]++; so therefore freq[X] is the number of times X occured.

.:.

I want to now pick out the 5 numbers that were generated the most frequently, and the 5 numbers that were generated
the least frequently.... Any ideas on how I would do this?

So basically I've created the following method:

Code:

```public static void getMostCommonNumbers(int [] freq) {     int [] mostFrequent;     /* INSERT CODE HERE */     System.out.print("\nThe numbers that appeared the most often were: ");         for(int k = 0; k < mostFrequent.length; k++)     {         System.out.print(mostFrequent[k] + " ");     }     System.out.println(); }```

Any help is much appreciated in this :).
• 12-18-2009, 10:36 PM
xcallmejudasx
send that array into a method that sorts. once sorted just take the first and last 5 elements from it.
• 12-18-2009, 10:41 PM
wtd_nielsen
hmm you could instead of using a int array, you could make an array that can contain a class that has a number and a frequence attribute (make a new class). Then when you run the getMostCommonNumbers method, you could make a new array that is sorted by frequence...just an idea..
• 12-19-2009, 08:18 AM
Hexbomber
I figured it out, by using nested for's... here is my solution, which works....
Code:

```public static void getMostCommonNumbers() {                 int count = 6;                 int [] high = new int[count];                   for (int i = 0; i < count; ++i)                   {                         high[i] = -1;                     }                   for (int i = 0; i < numFreq.length; ++i)                   {                     for (int j = 0; j < count; ++j)                     {                             if (high[j] != -1 && numFreq[i] > numFreq[high[j]])                             {                                 for (int k = count - 1; k > j; --k)                                 {                                                 high[k] = high[k - 1];                                         }                                 high[j] = i;                                 break;                               }                               else if (high[j] == -1)                               {                                 high[j] = i;                                 break;                               }                   } }```