This has been probably the most frustrating chapter yet with validation. I've tested numerous data sets with my algorithm. It tries starting with all words in the list and returns the longest result. It's worked with everything I've thrown at it, even the ones you guys have suggested. I think the most frustrating part of CodeGym is we don't get to see the dataset that's failing validation. I wish they would provide the test samples they use so I can SEE where my results differ from theirs. Since that's not possible, anyone have any explanations?
package com.codegym.task.task22.task2209;
/*
Make a word chain
*/
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Solution {
public static void main(String[] args) throws IOException {
List<String> words = new ArrayList<>();
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
BufferedReader fileReader = new BufferedReader(new FileReader(reader.readLine()));
reader.close();
while (fileReader.ready()) {
words.addAll(Arrays.asList(fileReader.readLine().trim().split(" ")));
}
fileReader.close();
StringBuilder result = getLine(words.toArray(new String[words.size()]));
System.out.println(result.toString());
}
public static StringBuilder getLine(String... words) {
if(words == null || words.length == 0)
return new StringBuilder();
List<StringBuilder> allWordCombos = new ArrayList<>();
for(int i = 0; i < words.length; i++) {
//Remember this code below. This was tricky to cast to ArrayList
//Arrays.asList returns List, and we can't just do (ArrayList<>) Arrays.asList(words);
List<String> remainingWords = new ArrayList<>(Arrays.asList(words));
StringBuilder result = new StringBuilder();
result.append(remainingWords.remove(i));
while(!remainingWords.isEmpty()) {
char lastChar = result.charAt(result.length() - 1);
String nextWord = findNextWord(remainingWords, lastChar);
if(nextWord != null) {
result.append(" "). append(nextWord);
remainingWords.remove(nextWord);
} else break;
}
allWordCombos.add(result);
}
StringBuilder finalResult = allWordCombos.get(0);
for(StringBuilder s : allWordCombos)
if(s.length() > finalResult.length())
finalResult = s;
return finalResult;
}
public static String findNextWord(List<String> remainingWords, char lastChar) {
for(String s : remainingWords)
if(Character.toLowerCase(lastChar) == Character.toLowerCase(s.charAt(0)))
return s;
return null;
}
}