java - Can't produce all permutations of a String (iteratively) -
so i'm working on java exercises, , 1 has caught attention trying produce permutations of string
using iteration. there plenty of examples online - however, lot of them seem complex , i'm not able follow.
i have tried using own method, when tested string of length 3 works fine. method (for each letter) keep moving letter along string, swapping whatever letter in front of it. e.g.
index: 012 string: abc (iteration 1) swap 'a' (index 0) letter after 'b' (index 0+1) : bac (iteration 2) swap 'a' (index 1) letter after 'c' (index 1+1) : bca (iteration 3) swap 'a' (index 2) letter after 'b' (index 0) : acb current permutations: abc (original), bac, bca, acb (iteration 3) swap 'b' (index 1) letter after 'c' (index 1+1) : acb (iteration 4) swap 'b' (index 2) letter after 'a' (index 0) : bca (iteration 5) swap 'b' (index 0) letter after 'c' (index 1) : cba current permutations: abc (original), bac, bca, acb, acb, cba ...
this how implemented in java:
string str = "abc"; // string permute char[] letters = str.tochararray(); // split string char array int setlength = factorial(letters.length); // amount of permutations = n! hashset<string> permutations = new hashset<string>(); // store permutations in set avoid duplicates permutations.add(str); // add original string set // algorithm described above (int = 0; < setlength; i++) { (int j = 0; j < letters.length; j++) { int k; if (j == letters.length - 1) { k = 0; } else { k = j + 1; } letters = swap(letters, j, k); string perm = new string(letters); permutations.add(perm); } }
the problem if input string of length 4, end 12 permutations (4x3) - if input string of length 5, end 20 permutations (5x4).
is there simple modification make algorithm every possible permutation? or particular method work strings of length 3?
appreciate feedback!
suppose input "abcd". how algorithm work
bacd
bacd
bcad
bcda
if observe carefully, "a" getting positioned @ indexes , following consecutive letter getting replaced "a". however, after algorithm has produced "bacd" - should followed "badc" also, missing output.
for string of length 4, when calculated number of permutations factorial, understand first position can occupied 4 characters, followed 3, 2 , 1. however, in case when first 2 positions occupied "ba" there 2 possibilities 3rd position, i.e. c , d. while algorithm correctly finds "cd", fails find "dc" - because, loop not break problem further subproblems, i.e. "cd" has 2 permutations, respectively "cd" , "dc".
thus, difference in count of permutations , actual answer increase length of string increases.
to break problems sub-problem , solve it, many algorithm uses recursion.
however, generate list of possible permutations of string iterative answers.
also, length of string grows, calculating number of permutation not advisable.
Comments
Post a Comment