All pastes #815718 Raw Edit

Miscellany

public text v1 · immutable
·published 2007-12-14 09:57 UTC
rendered paste body
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<String> addCharAtAllPosition(char a, String s) {
		Set<String> possibilities = new TreeSet<String>();
		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<String> addCharAtAllPosition(char a, Collection<String> strings) {
		Set<String> possibilities = new TreeSet<String>();
		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 à trouver nous même les arguments des fonctions
	 */
	public static Set<String> permut(String s) {
		Set<String> permutations = new TreeSet<String>();
		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);
			}
		}
	}
}