编辑:这是一个代码挑战。我实际上只是再次运行它,更具体的是代码是无用的。请参阅here和here。
我无法弄清楚我的代码到底出了什么问题。它通过了所有可见的测试用例,但未通过4/5隐藏的测试用例。
面临的挑战是尝试使用之前对话的历史记录(currentConversation
)预测给定对话的下一个字词conversations
)。如果历史对话的字词与currentConversation
匹配,请将其余的历史对话附加到currentConversation
。
这是我在Java中的代码:
public String[] chatBot(String[][] conversations, String[] currentConversation) {
int hmNumOfMatches = 0; // highest matched conversation's similar words to the current conversation
ArrayList<String> hmRestOfWords = new ArrayList<>(); // the rest of the words in the matched conversation
// for all given conversations
for (String[] pc : conversations) {
int numOfMatches = 0;
int indexOfLastMatchingWord = -1;
HashSet<String> uw = new HashSet<String>(); // stores the unique words in pc (possible conversation)
// for all words of possible conversation
for (int j = 0; j < pc.length; j++) {
String pw = pc[j]; // possible word
// exclude words that have already been accounted for
if (!uw.contains(pw)) {
// for all words in the current conversation
for (int i = 0; i < currentConversation.length; i++) {
String w = currentConversation[i];
if (w.compareTo(pw) == 0) {
numOfMatches++;
indexOfLastMatchingWord = j;
}
}
uw.add(pw);
}
}
ArrayList<String> restOfWords = new ArrayList<>();
// if there were matching words
if (indexOfLastMatchingWord != -1)
restOfWords = getRestOfWords(pc, indexOfLastMatchingWord);
else continue;
// set the highest number of matches if it has none
if (hmNumOfMatches == 0) {
hmNumOfMatches = numOfMatches;
hmRestOfWords.addAll(restOfWords);
}
// also update it if it's less then the current number of matches
if (hmNumOfMatches < numOfMatches) {
hmNumOfMatches = numOfMatches;
hmRestOfWords = restOfWords;
}
}
/**
* Create the answer
*/
String[] answer = new String[currentConversation.length + hmRestOfWords.size()];
int i;
// append the current conversation to the answer
for (i = 0; i < currentConversation.length; i++) {
answer[i] = currentConversation[i];
}
// and append the rest of the words from the matched historical conversation
for (int j = 0; j < hmRestOfWords.size(); j++) {
answer[i + j] = hmRestOfWords.get(j);
}
return answer;
}
public ArrayList<String> getRestOfWords(String[] pc, int indexOfLastMatchingWord) {
ArrayList<String> restOfWords = new ArrayList<String>();
for (int i = indexOfLastMatchingWord + 1; i < pc.length; i++) {
if (!restOfWords.contains(pc[i])) restOfWords.add(pc[i]);
}
return restOfWords;
}