i am trying to generate all the permutations of a given string.
the logic im using
suppose string =abcd
1) then i fix 'a'(and similarly each character.. first iteration - abcd, second-bacd, third-cabd.....)at first position in the first loop..
2) then generate strings by moving the second character ,i.e, 'b' at all the places.. like abcd,acbd,acdb...
3) then i replace the 3rd( 4th ,5th and so on ) character with the second charcter and repeat the second step again
4) i change abcd to bacd( n so for each character) and repeat steps 2,3...
now shouldn't this generate all the possible combinations..and also i use a tree set to remove duplicate entries... but somehow it is generating less permutations than there are actually..like for 4 characters, 20 permutations only...
here is the code for the same..
import java.util.*;
public class practice4 {
public static void main(String[] args) {
TreeSet t = new TreeSet();
String arr[] = new String[100];
int z = -1;
StringBuffer s5 = new StringBuffer("abcde");
for (int i = 0; i <= s5.length() - 1; i++) {
char ch = s5.charAt(0);
s5.setCharAt(0, s5.charAt(i));
s5.setCharAt(i, ch);
StringBuffer s3 = new StringBuffer(s5);
for (int j = 1; j <= s3.length() - 1; j++) {
StringBuffer s2 = new StringBuffer(s3);
// System.out.println(s2);
z++;
arr[z] = s2.toString();
for (int k = 1; k < s3.length() - 1; k++) {
char ch2 = s2.charAt(k);
s2.setCharAt(k, s2.charAt(k + 1));
s2.setCharAt(k + 1, ch2);
// System.out.println(s2);
z++;
arr[z] = s2.toString();
}
if (j >= s3.length() - 1)
break;
char ch3 = s3.charAt(1);
s3.setCharAt(1, s3.charAt(j + 1));
s3.setCharAt(j + 1, ch3);
}
System.out.println("dooone");
System.out.println(z);
for (int x = 0; x <= z; x++) {
t.add(arr[x]);
}
}
System.out.println(t.size());
Iterator i55 = t.iterator();
while (i55.hasNext()) {
System.out.println(i55.next());
}
}
}