I wrote a function for creating all possible translations of a source string, based on a multiple translation map. It works, but generates a lot of intermediate maps (see line marked with *). Is there a better solution? Maybe a more general solution to the "all possible combinations" problem?:
/**
* <p>Add to 'targets' all possible variations of 'source', with replacements defined by 'translationsMap'.
* <p>For example, after the following call:
* <p>addAllReplacements("put the X on the Y", {X => {"cake","egg"}, Y => {"table","chair"}, targets)
* <p>targets should contain the following strings:
* <p>"put the cake on the table", "put the cake on the chair", "put the egg on the table", "put the egg on the chair"
*/
public static void addAllReplacements (String source, Map<String, Set<String>> translationsMap, Set<String> targets) {
if (translationsMap.isEmpty()) {
// no more replacements:
targets.add(source);
} else {
// pick an entry from the map:
Entry<String, Set<String>> e = translationsMap.entrySet().iterator().next();
String text = e.getKey();
Set<String> translations = e.getValue();
// Create a new translation map, without the currently translated text, for the recursive call:
HashMap<String, Set<String>> newTranslationMap =
new HashMap<String, Set<String>>(translationsMap); // *
newTranslationMap.remove(text);
for (String translation: translations) {
addAllReplacements(
source.replace(text, translation),
newTranslationMap,
targets);
}
}
}