Any ideas?
Passes all but second to last task. How can my output match the requirements but someho I'm not using all words?
My test data:
//Test data in: Disney Okinawa Washington Yellowstone Auckland Kalamazoo Norfolk
//Test data out: Washington Norfolk Kalamazoo Okinawa Auckland Disney Yellowstone
package com.codegym.task.task22.task2209;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
public class Solution {
//Test data in: Disney Okinawa Washington Yellowstone Auckland Kalamazoo Norfolk
//Test data out: Washington Norfolk Kalamazoo Okinawa Auckland Disney Yellowstone
List<String> permutations = new ArrayList<>();
public static void main(String[] args) throws Exception {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String filename = reader.readLine();
BufferedReader bufferedReader = new BufferedReader(new FileReader(filename));
StringBuilder result = getLine(bufferedReader.readLine());
System.out.println(result.toString());
reader.close();
bufferedReader.close();
}
public static StringBuilder getLine(String... words) {
StringBuilder sb = new StringBuilder();
if (words.length == 0) return sb;
Solution s = new Solution();
String[] wordList = words[0].split(" ");
genPerm(s, 0, wordList.length, "");
ArrayList<String> biggestChain = new ArrayList<>();
for (int i = 0; i < s.permutations.size(); i++) {
ArrayList<String> wordChain = wordMatch(s.permutations.get(i), wordList);
if (biggestChain.isEmpty() || wordChain.size() > biggestChain.size()) {
biggestChain.clear();
biggestChain.addAll(wordChain);
}
if (biggestChain.size() == 5) break;
}
for (int i = 0; i < biggestChain.size(); i++) {
sb.append(biggestChain.get(i));
if (i != biggestChain.size() - 1)
sb.append(" ");
}
return sb;
}
public static void genPerm(Solution s, int currentIteration, int size, String usedNums) {
if (usedNums.length() == size) {
s.permutations.add(usedNums);
}
for (int i = 0; i < size; i++) {
if (usedNums.contains(("" + i))) continue;
genPerm(s, currentIteration + 1, size, usedNums + i);
}
}
public static ArrayList<String> wordMatch(String permNum, String[] wordList) {
//As soon as wordChain is broken e.g. second word cannot match the third end the routine and return the array list.
int[] index = new int[permNum.length()];
char[] c = permNum.toCharArray();
for (int i = 0; i < index.length; i++) {
index[i] = Character.getNumericValue(c[i]);
}
ArrayList<String> wordChain = new ArrayList<>();
wordChain.add(wordList[index[0]]);
for (int i = 0; i < c.length - 1; i++) {
if (charMatch(wordList[index[i]], wordList[index[(i + 1)]])) {
wordChain.add(wordList[index[(i + 1)]]);
} else {
break;
}
}
return wordChain;
}
public static boolean charMatch(String current, String next) {
char a = current.toLowerCase().charAt(current.length() - 1);
char b = next.toLowerCase().charAt(0);
return (a == b);
}
}