tags:

views:

147

answers:

1

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?

+4  A: 

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, 1);
    else
        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);
aioobe
thanks thanks very much
another way to count the occurrence of word is Collections.frequency, but in this case it will have a higher BigO.
Lars Andren
Good to know. I looked through the Arrays for that function :) I guess one could go through Arrays.asList to get the shortest solution :) ...or do it with Scala ;)
aioobe
ok i have meet following problem too for example there is given two text find longest string that occur in both i think we should cretate string array where we should put common srings and then compare their length and which length will be largest print it is there fast method?
@david: that's the classic LCS http://en.wikipedia.org/wiki/Longest_common_substring
polygenelubricants
I'm not sure this answers the question - printing words in decreasing frequency. The iteration order of HashMap is undefined, and so the words will be printed in some arbitrary order.
mdma