// Ray McDougall // 11/22/13 // CSE 143x // TA: Kevin Quinn // Programming Assignment #9 // // This management class for the AnagramMain program will search a // given word list for all possible sets of anagrams of a given phrase, // up to a given word count cap. As this is performed through an // exhaustive search, all possible permutations of each anagram combination // are returned. import java.util.*; public class AnagramSolver { List dictionary; Map inventories; // initializes the necessary word lists; stores each word // in the given dictionary with its letter inventory public AnagramSolver(List list) { dictionary = new ArrayList(); inventories = new HashMap(); for (String word : list) { dictionary.add(word); LetterInventory letters = new LetterInventory(word); inventories.put(word, letters); } } // pre: the max word count must not be negative, otherwise throws IllegalArgumentException // post: returns all anagram combinations up to the given // max word count public void print(String s, int max) { if (max < 0) { throw new IllegalArgumentException(); } int level; // ensure that a max of zero will be a special case if (max == 0) { level = -1; } else { level = max; } LetterInventory target = new LetterInventory(s); prune(dictionary, target); List result = new ArrayList(); search(target, result, level + 1); } // clears the word list of any unnecessary words (no possible anagrams) private static void prune(List list, LetterInventory target) { for (String word : list) { LetterInventory temp = new LetterInventory(word); if (target.subtract(temp) == null) { list.remove(temp); } } } // prints the output of each possible anagram set directly to the console private void search(LetterInventory target, List result, int level) { // make a pass through each word in the pruned dictionary for (Map.Entry currentEntry : inventories.entrySet()) { // make sure the current word will fit into the possible anagram set // and we are not going too many levels down (based on the max word count) if (target.subtract(currentEntry.getValue()) != null && level != 1) { result.add(currentEntry.getKey()); // outputs a solution if it has been found, otherwise go down another level if (target.subtract(currentEntry.getValue()).isEmpty()) { System.out.println(result.toString()); } else { search(target.subtract(currentEntry.getValue()), result, level - 1); } result.remove(currentEntry.getKey()); } } } }