| 12
 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
 39
 40
 
 | import java.util.*;
 
public class Combi {
	public static void main(String[] args) {
		// Paramétrage
		List<String> alphabet = Arrays.asList("a", "b", "c", "d", "e");
		int length = 3;
 
		// Exécution
		List<String> result = combi(alphabet, length);
 
		// Affichage du résultat
		System.out.println(result);
	}
 
	// Démarrage de la boucle.
	static List<String> combi(List<String> alphabet, int length) {
		if (length < 0 || alphabet.length() < length) { throw new IllegalArgumentException(); }
		if (length == 0) {
			return Collections.emptyList();
		}
		List<String> result = new ArrayList<String>();
		combi2(alphabet, length, result, new StringBuilder());
		return result;
	}
 
	// Méthode de calcul, récursive.
	private static void combi2(List<String> alphabet, int length, List<String> result, StringBuilder buffer) {
		int bufferLength = buffer.length();
		for (int i = 0, size = alphabet.size(); i < size && length <= size - i; i++) {
			buffer.append(alphabet.get(i));
			if (length == 1) {
				result.add(buffer.toString());
			} else {
				combi2(alphabet.subList(i + 1, size), length - 1, result, buffer);
			}
			buffer.setLength(bufferLength);
		}
	}
} | 
Partager