Once again, my solution produces a correct output, but it is not accepted.
Except for using Math.random() - which is not an analytical way to a solution - where
could I have gone wrong this time?
Besides... the lection was about StringBuilder. Is this task about StringBuilder, too?
PS: sorry for the commented out code. I thought I uploaded an updated version, but
never mind...
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.*;
public class Solution {
public static void main(String[] args) throws IOException {
String fileName;// = "f2209.txt";
List<String> words = new ArrayList<>();
try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in))) {
fileName = bufferedReader.readLine();
}
try (BufferedReader reader = new BufferedReader(new FileReader(fileName))) {
while (reader.ready()) {
words.addAll(Arrays.asList(reader.readLine().split(" ")));
}
}
StringBuilder result = getLine(words.toArray(new String[0]));
System.out.println(result.toString());
}
public static StringBuilder getLine(String... words) {
//System.out.println(Arrays.toString(words));
//ConnectedWord: checks first and last character, creates a list of connection candidates
List<ConnectedWord> connectedWords = new ArrayList<>();
for (String word : words) {
ConnectedWord connectedWord = new ConnectedWord(word);
connectedWords.add(connectedWord);
}
//check for candidates
for (ConnectedWord cwOuter : connectedWords) {
for (ConnectedWord cwInner : connectedWords) {
if (cwOuter == cwInner) { //check reference
continue;
}
if (cwOuter.lastChar == cwInner.firstChar) {
cwOuter.candidates.add(cwInner);
}
}
}
/*for (ConnectedWord cw : connectedWords) {
System.out.println(cw.toString());
}*/
//Set<List<String>> combinations = new HashSet<>();
int maxSize = 0;
List<String> maxCombination = null;
for (ConnectedWord cw : connectedWords) {
List<String> combination = new ArrayList<>();
ConnectedWord current = cw;
for (int i = 0; i < connectedWords.size(); i++) {
combination.add(current.word);
int currentCandidatesSize = current.candidates.size();
if (currentCandidatesSize == 0) {
break;
}
current = current.candidates.get((int)(Math.random() * currentCandidatesSize));
}
if (maxSize < combination.size()) {
maxSize = combination.size();
maxCombination = combination;
}
//combinations.add(combination);
//System.out.println(combination);
}
//System.out.println(maxCombination);
StringBuilder sb = new StringBuilder();
if (words.length == 0) {
return sb;
}
if (maxCombination != null && !maxCombination.isEmpty()) {
sb.append(String.join(" ", maxCombination));
}
return sb;
}
}