import java.util.HashMap;
import java.util.ArrayList;

public class NGramTracker {
  
  // hashmap keys strings to arraylists
  protected HashMap<String, ArrayList<String>> grams =
    new HashMap<String, ArrayList<String>>();
  protected int n = 3;
  
  public NGramTracker(int n_) {
    n = n_;
  }
  
  public void feed(String word) {
    
    // walk through string, finding each group of n characters
    for (int i = 0; i < word.length() - n + 1; i++) {
      String gram = word.substring(i, i+n);
      
      // if we've already seen this n-gram, append the current to the list
      if (grams.containsKey(gram)) {
        ArrayList<String> glist = grams.get(gram);
        glist.add(word);
      }
      // otherwise, create a new list, and put it into the hashmap with
      // the current n-gram as a key
      else {
        ArrayList<String> newlist = new ArrayList<String>();
        newlist.add(word);
        grams.put(gram, newlist);
      }
    }
    
  }
  
  // returns all words for the given n-gram (ArrayList without a type so
  // Processing can understand it)
  public ArrayList getWordsForGram(String gram) {
    if (grams.containsKey(gram)) {
      return new ArrayList(grams.get(gram));
    }
    else {
      // return empty list if n-gram wasn't found
      return new ArrayList();
    }
  }
  
}
