Ich habe eine Liste der Elemente {a, b, c, d} und muss alle möglichen Kombinationen generieren, wenn,
Wenn wir die Möglichkeiten nutzen, sollte es sein,
n=4, number of items
total #of combinations = 4C4 + 4C3 + 4C2 + 4C1 = 15
Ich habe die folgende rekursive Methode verwendet:
private void countAllCombinations (String input,int idx, String[] options) {
for(int i = idx ; i < options.length; i++) {
String output = input + "_" + options[i];
System.out.println(output);
countAllCombinations(output,++idx, options);
}
}
public static void main(String[] args) {
String arr[] = {"A","B","C","D"};
for (int i=0;i<arr.length;i++) {
countAllCombinations(arr[i], i, arr);
}
}
Gibt es eine effizientere Möglichkeit, dies zu tun, wenn das Array groß ist?
Betrachten Sie die Kombination als eine binäre Folge. Wenn alle 4 vorhanden sind, erhalten wir 1111, wenn das erste Alphabet fehlt, erhalten wir 0111 usw. Für n Alphabete haben wir also 2 ^ n -1 (seit 0) ist nicht enthalten) Kombinationen.
Wenn in Ihrer erzeugten Binärsequenz der Code 1 ist, ist das Element vorhanden, andernfalls ist es nicht enthalten. Nachfolgend finden Sie die Proof-of-Concept-Implementierung:
String arr[] = { "A", "B", "C", "D" };
int n = arr.length;
int N = (int) Math.pow(2d, Double.valueOf(n));
for (int i = 1; i < N; i++) {
String code = Integer.toBinaryString(N | i).substring(1);
for (int j = 0; j < n; j++) {
if (code.charAt(j) == '1') {
System.out.print(arr[j]);
}
}
System.out.println();
}
Und hier ist eine generische wiederverwendbare Implementierung:
public static <T> Stream<List<T>> combinations(T[] arr) {
final long N = (long) Math.pow(2, arr.length);
return StreamSupport.stream(new AbstractSpliterator<List<T>>(N, Spliterator.SIZED) {
long i = 1;
@Override
public boolean tryAdvance(Consumer<? super List<T>> action) {
if(i < N) {
List<T> out = new ArrayList<T>(Long.bitCount(i));
for (int bit = 0; bit < arr.length; bit++) {
if((i & (1<<bit)) != 0) {
out.add(arr[bit]);
}
}
action.accept(out);
++i;
return true;
}
else {
return false;
}
}
}, false);
}
Dieser Artikel stammt aus dem Internet. Bitte geben Sie beim Nachdruck die Quelle an.
Bei Verstößen wenden Sie sich bitte [email protected] Löschen.
Lass mich ein paar Worte sagen