|
| 1 | +/** |
| 2 | + * Read in a list of words from standard input and print out the most frequently |
| 3 | + * occurring word that has length greater than a given threshold |
| 4 | + * The `FrequencyCounter` class provides a client for reading in a sequence |
| 5 | + * of words and printing a word(exceeding a given length) that occurs most |
| 6 | + * frequently. It is useful as a test client for various symbol table |
| 7 | + * implementation. |
| 8 | + * |
| 9 | + */ |
| 10 | +public class FrequencyCounter { |
| 11 | + private FrequencyCounter() {} |
| 12 | + |
| 13 | + // reads in a cli integer and sequence of words from standard input and prints |
| 14 | + // out a word(whose length exceeds the threshold) that occurs most frequently |
| 15 | + // standard output. It also prints out the number of words whose length exceeds |
| 16 | + // the threshold and the number of distinct such words. |
| 17 | + public static void main(String[] args) { |
| 18 | + int distinct = 0, words = 0; |
| 19 | + int minLen = Integer.parseInt(args[0]); |
| 20 | + ST<String, Integer>st = new ST<String, Integer>(); |
| 21 | + |
| 22 | + while(!StdIn.isEmpty()) { |
| 23 | + String key = StdIn.readString(); |
| 24 | + if(key.length() < minLen) |
| 25 | + continue; |
| 26 | + words++; |
| 27 | + if(st.contains(key)) |
| 28 | + st.put(key, st.get(key) + 1); |
| 29 | + else { |
| 30 | + st.put(key, 1); |
| 31 | + distinct++; |
| 32 | + } |
| 33 | + } |
| 34 | + |
| 35 | + // find a key with the highest frequency count |
| 36 | + String max = ""; |
| 37 | + st.put(max, 0); |
| 38 | + for(String word : st.keys()) { |
| 39 | + if(st.get(word) > st.get(max)) |
| 40 | + max = word; |
| 41 | + } |
| 42 | + |
| 43 | + StdOut.println(max + " " + st.get(max)); |
| 44 | + StdOut.println("distinct = " + distinct); |
| 45 | + StdOut.println("words = " + words); |
| 46 | + } |
| 47 | +} |
0 commit comments