import java.io.*; import java.util.*; public class WordJumble { private static String sortedWord(String word) { String sortedWord = ""; // Sort the letters of word while (word.length() != 0) { // lleoh // find alpha earliest letter: e int sIndex = 0; for (int i = 0; i < word.length(); i++) { if (word.charAt(i) < word.charAt(sIndex)) { sIndex = i; } } sortedWord += word.charAt(sIndex); word = word.substring(0, sIndex) + word.substring(sIndex + 1); } return sortedWord; } private static Map> createDictionary(Scanner words) { /* OUR FIRST VERSION USED A SET DICTIONARY INSTEAD OF A MAP: Set dictionary = new HashSet(); while (words.hasNext()) { dictionary.add(words.next()); } */ Map> dictionary = new HashMap>(); while (words.hasNext()) { String word = words.next(); String sortedWord = sortedWord(word); if (!dictionary.containsKey(sortedWord)) { dictionary.put(sortedWord, new TreeSet()); } dictionary.get(sortedWord).add(word); } return dictionary; } private static String getWord(Scanner console) { System.out.print("Word to Unscramble (q to quit): "); return console.next().toLowerCase(); } private static Set search(Map> dictionary, String sortedWord) { /* OUR FIRST VERSION USED A SET DICTIONARY INSTEAD OF A MAP: Set results = new TreeSet(); for (String word : dictionary) { if (sortedWord(word).equals(sortedWord)) { results.add(word); } } return results; */ if (!dictionary.containsKey(sortedWord)) { return new TreeSet(); } return dictionary.get(sortedWord); } public static void main(String[] args) throws FileNotFoundException { System.out.println("Welcome to the cse143 word jumble solver."); Scanner input = new Scanner(new File("dictionary.txt")); /* ----------READ IN DICTIONARY---------- * First Attempt: Set, where * the items are the words * Second Attempt: Map>, where * the keys are sorted versions of words (e.g. aadm) * the values are sets of words (e.g. [adam, mada]) */ Map> dictionary = createDictionary(input); // while I want to unscramble a word... // Read in word to unscramble Scanner console = new Scanner(System.in); String word = getWord(console); while (!word.equals("q")) { // Print out the scramble and the sorted scramble System.out.println("Scramble: " + word); String sortedWord = sortedWord(word); System.out.println("Sorted Scramble: " + sortedWord); // Search through dictionary for matching words System.out.println("Answers: " + search(dictionary, sortedWord)); // Get a new word word = getWord(console); } } }