Question

In "Programming Pearls" I have met the following problem. The question is this: "print words in order of decreasing frequency". As I understand problem is this. Suppose there is a given string array, let's call it s (words I have chosen randomly, it does not matter),

String s[]={"cat","cat","dog","fox","cat","fox","dog","cat","fox"};

We see that string "cat" occurs 4 times, "fox" 3 times and "dog" 2 times. So the desired result will be this:

cat
fox
dog

I have written the following code in Java:

import java.util.*;
public class string {
   public static void main(String[] args){
      String s[]={"fox","cat","cat","fox","dog","cat","fox","dog","cat"};
      Arrays.sort(s);
      int counts;
      int count[]=new int[s.length];
      for (int i=0;i<s.length-1;i++){
         counts=1;
         while (s[i].equals(s[i+1])){
            counts++;
         }
         count[i]=counts;
      }
   }
}

I have sorted the array and created a count array where I write the number of occurrences of each word in array.

My problem is that somehow the index of the integer array element and the string array element is not the same. How can I print words according to the maximum elements of the integer array?

Was it helpful?

Solution

To keep track of the count of each word, I would use a Map which maps a word to it's current count.

String s[]={"cat","cat","dog","fox","cat","fox","dog","cat","fox"};

Map<String, Integer> counts = new HashMap<String, Integer>();
for (String word : s) {
    if (!counts.containsKey(word))
        counts.put(word, 0);
    counts.put(word, counts.get(word) + 1);
}

To print the result, go through the keys in the map and get the final value.

for (String word : counts.keySet())
    System.out.println(word + ": " + (float) counts.get(word) / s.length);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top