001package algs35;
002import stdlib.*;
003/* ***********************************************************************
004 *  Compilation:  javac FrequencyTable StdIn.java
005 *  Execution:    java FrequencyTable < words.txt
006 *
007 *  Read in a list of words from standard input and print out
008 *  each word and the number of times it appears.
009 *
010 *  % java Frequency < mobydick.txt | sort -rn | more
011 *  13967 the
012 *  6415 of
013 *  6247 and
014 *  4583 a
015 *  4508 to
016 *  4037 in
017 *  2911 that
018 *  2481 his
019 *
020 *************************************************************************/
021
022public class XFrequencyTable<K extends Comparable<? super K>> {
023
024        private final ST<K, Integer> st = new ST<>();
025
026        // add 1 to the number of times key appears
027        public void hit(K key) {
028                Integer freq = st.get(key);
029                if (freq == null) st.put(key, 1);
030                else              st.put(key, freq + 1);
031        }
032
033        // return the number of times the key appears
034        public int count(K key) {
035                Integer freq = st.get(key);
036                if (freq == null) return 0;
037                else              return freq;
038        }
039
040        // print all the keys to standard output
041        public void show() {
042                for (K key : st.keys())
043                        StdOut.println(st.get(key) + " " + key);
044        }
045
046
047        public static void main(String[] args) {
048                StdIn.fromFile ("data/mobydick.txt");
049
050                XFrequencyTable<String> f = new XFrequencyTable<>();
051                while (!StdIn.isEmpty()) {
052                        String key = StdIn.readString();
053                        f.hit(key);
054                }
055                f.show();
056
057
058        }
059}
060