1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
|
import java.util.Arrays;
import java.util.HashMap;
import java.util.Set;
public class Main {
static void permut(String[] words) {
//zählen, welches Wort wie oft vorkommt
HashMap<String, Integer> dict = new HashMap<String, Integer>();
for (String word : words) {
if (!dict.containsKey(word)) {
dict.put(word, 0);
}
dict.put(word, dict.get(word) + 1);
}
//Permutationen bilden
permutRecurs(dict, dict.keySet(), 0, new String[words.length]);
}
static void permutRecurs(HashMap<String, Integer> wordCount, Set<String> keys, int index, String[] sequence) {
//Alle Wörter verwendet?
if (index == sequence.length) {
System.out.println(Arrays.toString(sequence));
}
for (String word : keys) {
//noch ein Wort übrig?
if (wordCount.get(word) > 0) {
wordCount.put(word, wordCount.get(word) - 1); //Wort als verwendet markieren
sequence[index] = word; //und Position des Wortes speichern
permutRecurs(wordCount, keys, index + 1, sequence); //rekursiver Aufruf
wordCount.put(word, wordCount.get(word) + 1); //nach der Rekursion Wort wieder zur Verwendung freigeben
}
}
}
public static void main(String[] args) {
permut(new String[] { "Matse", "Milch", "Nett", "Ungarn", "Matse", "Milch", "Nett", "Ungarn" });
}
} |