Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import edu.princeton.cs.introcs.*;
- import edu.princeton.cs.algs4.ST;
- import edu.princeton.cs.algs4.SequentialSearchST;
- import edu.princeton.cs.algs4.LinearProbingHashST;
- import java.lang.reflect.Constructor;
- import java.util.HashMap;
- import java.util.TreeMap;
- import java.util.Map;
- // This can be used to test symbol table implementations.
- public class FrequencyCounter {
- interface SymbolTable<K,V> {
- boolean contains(K key);
- void put(K Key,V value);
- V get(K Key);
- Iterable<K> keys();
- }
- public static class AdaptedSequentialSearchST
- extends SequentialSearchST<String,Integer>
- implements SymbolTable<String,Integer> {
- }
- public static class AdaptedST
- extends ST<String,Integer>
- implements SymbolTable<String,Integer> { }
- public static class AdaptedLinearProbingHashST
- extends LinearProbingHashST<String,Integer>
- implements SymbolTable<String,Integer> { }
- static abstract class AdaptedMap
- implements SymbolTable<String,Integer> {
- protected Map<String,Integer> map;
- public Iterable<String> keys() { return map.keySet(); }
- public Integer get(String key) { return map.get(key); }
- public void put(String key,Integer value) { map.put(key,value); }
- public boolean contains(String key) {
- return map.containsValue(key); }
- }
- public static class AdaptedHashMap extends AdaptedMap {
- public AdaptedHashMap() { this.map = new HashMap<String,Integer>(); } }
- public static class AdaptedTreeMap extends AdaptedMap {
- public AdaptedTreeMap() { this.map = new TreeMap<String,Integer>(); } }
- // TODO Tries
- private static void run(int minlen,String symbolTableClassName)
- throws Exception {
- Class<?> cl = Class.forName(
- "danielf.src.java.programs.FrequencyCounter$Adapted" +
- symbolTableClassName);
- Constructor<?> constructor = cl.getConstructor();
- SymbolTable<String,Integer> st =
- (SymbolTable<String,Integer>) constructor.newInstance();
- while (!StdIn.isEmpty())
- {
- String word = StdIn.readString();
- if (word.length() < minlen) continue;
- if (!st.contains(word)) st.put(word,1);
- else st.put(word,st.get(word)+1);
- }
- String max = "";
- st.put(max,0);
- for (String word : st.keys()) {
- if (st.get(word) > st.get(max))
- max = word;
- }
- StdOut.println(max + " " + st.get(max));
- }
- public static void main(String[] args) throws Exception {
- try {
- run(Integer.parseInt(args[0]),args[1]);
- } catch (ClassNotFoundException e) {
- System.err.println("ClassNotFoundException: " + e.getMessage());
- } catch (NoSuchMethodException e) {
- System.err.println("NoSuchMethodException: " + e.getMessage());
- } catch (InstantiationException e) {
- System.err.println("InstantiationException: " + e.getMessage());
- }
- }
- //class SymbolTable {
- // private
- //}
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement