I’ve made an anagram method to create all the possible combinations of a word, but I’d like to be able to check every letter combination.
For example: eastern would produce other variations such as earnest, but I’d also like it to produce variations such as east and eat and ate.
I already have a working dictionary checking whether the combinations are in the dictionary.
public void printAnagrams(String prefix, String word)
{
if(word.length() == 1) {
if (words.contains(prefix+word))
System.out.println(prefix + word);
}
else
{
for(int i = 0; i < word.length(); i++)
{
String current = word.substring(i, i + 1);
String before = word.substring(0, i);
String after = word.substring(i+1);
printAnagrams(prefix + current, before + after);
}
}
}
Have a set of
chars[can be achar[]] and “guess” which is the next letter, and append it to an intermediatesolStringBuilder, which holds the current substring. Invoke the algorithm recursively to find out next chars of the solution.Have an index
ito indicate which chars can be used [all chars “right” toi].At each iteration – print the resulting string, even if you did not the maximal length.
Pseudo code:
Notes:
charsis a set, so if a certain char appears more then once – you are going to have duplicates, but it will still work [generate all possibilities]