Ok, the real problem is slightly more complicated because it uses some classes that I’ve written instead of Strings, but it can be imagined like this: If you have a list of 700ish 3-letter words, how can I find every combination that can be formed by linking 5 of these words together by their first and last letters, i.e., CAT TOW WAR RAD DOG would be a success but so would CAT TOW WAR RAG GOD, and so on.
So far I have something like this:
for(int i = 0; i < list.size(); i++){
String temp = chainMaker(list.get(i), list, used, temp);
}
public String chainMaker(String toAdd, ArrayList<String> unused,
ArrayList<String> used, String result){
if(result.size() >= 15)
return result;
else{
if(result.canAdd(toAdd))
result.add(toAdd);
used.add(toAdd);
return chainMaker(unused.remove(0), unused, used, result);
}
return result;
}
But this just keeps adding the producing rubbish. I’m terrible at recursive backtracking and I think that if I can just make this example work, I’ll finally understand this concept.
Please help me smart people!
Here’s a C++ implementation, but I think the logic is obvious. Just ask if you don’t understand something.
If you can only use a word as many times as it appears in the list, then just use a counting vector subtract the count of that word every time you use it.