WordSplitPrinter,
WordSplit Printer Material from Lecture 09 will be helpful here. In lecture, we talked about how we can use recursion exploration to print out all permutations of a given string. For example, we could use recursion on the input “goat” to print out: tgoa tgao toga goat gota gaot gato gtoa gtao ogat ogta oagt oatg otga otag agot agto aogt aotg atgo atog toag tago taog Most of these aren’t actual anagrams, because they’re gibberish. We could check which are actual words (like “toga”), but that wouldn’t be enough. There are also cases like “atgo” where the full string isn’t a word, but we can break it into the separate words “at” and “go”. To find all anagrams, then, we need to find the ways we can take one of these permutations and split it into separate English words. That’s where your method, findWordsplits, comes in: public void findWordSplits(String input, TreeSet
WordSplitPrinter.java
package edu.csc220.recursion;
import java.io.*;
import java.util.*;
public class WordSplitPrinter {
/**
* Finds and prints out every possible way to split the input String into individual, valid English words (including
* if input is itself a single valid word). You must call printWordSplit below to actually print out the results.
*/
public void findWordSplits(String input, TreeSet allWords) {
// TODO: Implement this.
}
/** Prints out a word split, i.e. one particular arrangement of words. This is implemented for you! */
private void printWordSplit(ArrayList words) {
if (words.isEmpty()) {
System.out.println("(empty word list)");
} else {
System.out.print(words.get(0));
for (int i = 1; i < words.size(); i++) {
System.out.print(" " + words.get(i));
}
System.out.println();
}
}
public static void main(String[] args) {
TreeSet dictionary = readWords();
WordSplitPrinter wordSplitPrinter = new WordSplitPrinter();
// Expected to print out:
// i saw a bus
// i saw ab us
// is aw a bus
// is aw ab us
wordSplitPrinter.findWordSplits("isawabus", dictionary);
}
// Reads the "words.txt" file and returns the words in a TreeSet. This is completely implemented for you!
private static TreeSet readWords() {
TreeSet allWords = new TreeSet<>();
try {
BufferedReader bufferedReader = new BufferedReader(new FileReader("words.txt"));
String line;
while ((line = bufferedReader.readLine()) != null) {
if (line.trim().isEmpty()) {
continue;
}
allWords.add(line.toLowerCase());
}
bufferedReader.close();
} catch (IOException exception) {
throw new RuntimeException(exception);
}
return allWords;
}
}