I\'m making a word unscrambler in java. Right now I have a program that can print all rearrangements of 3 letters chosen from a word with 3 or more letters (no repeats). So for
I will not give you the actual code, but this should give you the idea how the recursion can look like (I believe there are other way to do it recursively :P )
void findAllCombination(String tmpResult,
String rawString,
int noOfChar,
List allCombinations) {
if (tmpResult.size() == noOfChar) {
allCombinations.add(tmpResult );
} else {
for (i in 0 to rawString.size()) {
findAllCombination(tmpResult + rawString[i],
rawString.removeCharAt(i),
noOfChar,
allCombinations);
}
}
}
List foo(String input, int level) {
List allResults = ...;
findAllCombination("", input, level, allResults);
return allResults;
}
The main recursion part is the findAllCombination
. The idea is strict forward. For way to find all permutation is, for the rawString input that we have, we take out the character one by one, and append to the previously found tmpResult, and use that tmpResult to do further processing. Once we hit the point that the tmpResult is long enough, then we put the tmpResult to the result allCombinations
list.
(foo() method is here just to make your invocation easier :P Codes that actually do the works is only 6 lines, excluding lines with only brackets and ignoring lines that I break intentionally for better readability )