import java.security.InvalidParameterException; import java.util.Collection; import java.util.Set; import java.util.TreeSet; public class Permut { /* * Ajoute la lettre donnée en paramètre à la position * index de s. * */ public static String addCharAtIndex(char a, String s, int index) { if(index < 0) { throw new InvalidParameterException("Index must be a nat"); } if(index >= s.length()) { return s+a; } StringBuilder sb = new StringBuilder(); for(int i = 0; i < s.length(); i++) { if(i == index) { sb.append(a); } sb.append(s.charAt(i)); } return sb.toString(); } /* * Ajoute la lettre donnée en paramètre à * toutes les positions possibles de la chaine. * Pour chaque cas, une nouvelle chaine estajouté * à la liste des retours. * Ex avec'a' et "bc" : * - abc * - bac * - bca * */ public static Set addCharAtAllPosition(char a, String s) { Set possibilities = new TreeSet(); for(int i = 0; i <= s.length(); i++) { possibilities.add(addCharAtIndex(a, s, i)); } return possibilities; } /* * La même méthode que précedemment, mais on l'applique à une liste d'entrée */ public static Set addCharAtAllPosition(char a, Collection strings) { Set possibilities = new TreeSet(); if(strings.size() == 0) { possibilities.add(new String(new char[] {a})); } else { for(String s : strings) { possibilities.addAll(addCharAtAllPosition(a, s)); } } return possibilities; } /* * On est pret à trouer nous même nos arguments */ public static Set permut(String s) { Set permutations = new TreeSet(); for(int i = 0; i < s.length(); i++) { permutations = addCharAtAllPosition(s.charAt(i), permutations); } return permutations; } public static void main(String[] args) { if(args.length > 0) { for(String s : Permut.permut(args[0])) { System.out.println(s); } } } }