The purpose for my class of data structures is to find the shortest path from one word to another.
i.e. Start: bleed → blend → blond → End: blood, with a cost of 3.
I am given a list of words that I need to group using a map. Where:
Key: word length, Meaning: a set of all words with this length.
I have already finished the program, but I think I can improve the performance if I change the way the sets are stored on the map. Right now I am browsing a text file and saving every single word in an ArrayList, then browsing through an ArrayList and saving all the words of length x in the set, removing every word from the list. I continue from the first element in the ArrayList until the List is empty.
I was wondering if I can do this sorting while I am reading in a file, and generally avoid ArrayList.
This is the code I have:
ArrayList<String> wordList = new ArrayList<String>();
Map<Integer, Set> setMap = new HashMap<Integer, Set>();
Graph pathGraph = new Graph();
private void readFile(String file) {
try {
FileReader f = new FileReader(file);
BufferedReader reader = new BufferedReader(f);
String line = "";
while ((line = reader.readLine()) != null) {
wordList.add(line);
}
} catch (Exception e) {
System.out.println("No file found.");
}
}
private void mapMaker() {
int wordLength = 1;
Set<String> wordSet = new HashSet<String>();
while (!wordList.isEmpty()) {
wordSet = setBuilder(wordLength);
if (!wordSet.isEmpty()) {
setMap.put(wordLength, wordSet);
}
wordLength++;
}
}
private Set<String> setBuilder(int x) {
Set<String> wordSet = new HashSet<String>();
int counter = 0;
while (counter < wordList.size()) {
if (wordList.get(counter).length() == x) {
wordSet.add(wordList.get(counter));
wordList.remove(counter);
} else {
counter++;
}
}
return wordSet;
}
Thank you for any input.
source
share