Thursday, July 30, 2009

String permutation algorithm?

Hi all,





I found on Wikipedia a short and nice algorithm which is suppose to find all permutations of characters in a string. For example, for the string ABC (3! = 6 permutations) = ABC, ACB, BAC, BCA, CAB and CBA.





Here is the Wikipedia algorithm


function permutation(k, s) {


var int factorial:= 1;


for j = 2 to length(s) {


factorial := factorial* (j-1);


swap s[j - ((k / factorial) mod j)] with s[j];


}


return s;


}





Here in my code in C#


public static T[] Permutation%26lt;T%26gt;(int k, T[] array) {


int factorial = 1;


for (int j = 2; j %26lt; array.Length; j++) {


factorial *= (j - 1);


int pos = j - ((k / factorial) % j);





T temp = array[pos];


array[pos] = array[j];


array[j] = temp;


}





return array;


}





However, it seem that I did a mistake in my code or the algorithm is wrong. Could you please help me to find a solution to my problem? Tell me what I forgot or what is missing in this algorithm.





Thank!

String permutation algorithm?
Try j %26lt;= array.Length





Also, as MathGuy said, this will only give you kth permutation. To generate them all with this code, would be slow. I believe I suggested an algorithm which works for generating all of them, but it seems that Question has been deleted.





permutations(str, s)


-If s is undefined, make s an empty string: ""


-If str is an empty string, return array with one element, s


-Make an array, p, to hold the permutations.


-Loop through each character of str.


--- t = s concatenated with the character


--- leftovers = str with the character removed


--- Add permutations(leftovers, t) to Array p


-Return Array p
Reply:The algorithm that you found is a little simple for calculating permutations.





I have uploaded a c# class here:


http://71.18.144.105/Class1.cs





The reference for the class is:


http://msdn2.microsoft.com/en-us/library...

cyclamen

No comments:

Post a Comment