001 package aima.util; 002 003 import java.util.Hashtable; 004 import java.util.Set; 005 006 /** 007 * @author Ravi Mohan 008 * 009 */ 010 011 public class FrequencyCounter<T> { 012 private Hashtable<T, Integer> counter; 013 014 public FrequencyCounter() { 015 counter = new Hashtable<T, Integer>(); 016 } 017 018 public Integer getCount(T key) { 019 Integer value = counter.get(key); 020 if (value == null) { 021 return 0; 022 } 023 return value; 024 } 025 026 public void incrementFor(T key) { 027 Integer value = counter.get(key); 028 if (value == null) { 029 counter.put(key, 1); 030 } else { 031 counter.put(key, value + 1); 032 } 033 } 034 035 public Double probabilityOf(T key) { 036 Integer value = getCount(key); 037 if (value == 0) { 038 return 0.0; 039 } else { 040 Double total = 0.0; 041 for (T k : counter.keySet()) { 042 total += getCount(k); 043 } 044 return value / total; 045 } 046 } 047 048 @Override 049 public String toString() { 050 return counter.toString(); 051 } 052 053 public Set<T> getStates() { 054 return counter.keySet(); 055 } 056 057 }