Is there any algorithm available for this one :
From a group of characters like :
a,@,n,M,O,f,D,),`,~,;,N,*,8,2,],2........ goes one . There are abou
First be aware that the number of possible permutations is in O(n^k)
(Choose(n,k) = n!/(k!*(n-k)!)
to be exact) where n
is the number of characters and k
is the desired length. Since it is exponential it could easily grow out of reach.
A general algorithm for achieving these combinations is using recursion and explore all possibilites up to this length. At each level you "guess" which character you will use next, place it, remove it from the list of available chars and recurse to solve the smaller problem (finding permutation up to length-1
).
private static void printPermutations(char[] chars, int idx, List candidate, int length) {
if (length == candidate.size()) {
System.out.println(candidate);
return;
}
for (int i = idx; i < chars.length; i++) {
candidate.add(chars[i]);
//set the selected element out of reach:
char temp = chars[idx];
chars[idx] = chars[i];
chars[i] = temp;
//recurse:
printPermutations(chars, idx+1, candidate, length);
//clean up environment:
temp = chars[i];
chars[i] = chars[idx];
chars[idx] = temp;
candidate.remove(candidate.size()-1);
}
}
public static void printPermutations(char[] chars, int length) {
printPermutations(chars, 0, new LinkedList(), length);
}