C# implementation of Heap's algorithm doesn't work -


i've attempted write implementation of heap's algorithm in c# isn't working correctly. i'm trying create general-purpose implementation find permutations of string, , add them list.

i'm starting out this:

list<string> permutations = new list<string>(); generateheappermutations(3, "abc", permutations);  foreach (var p in permutations) {     console.writeline(p); }  console.readkey(); 

and here's implementation:

public static void generateheappermutations(int n, string s, list<string> slist) {     if (n == 1)     {         slist.add(s);     }     else     {         (int = 0; < n - 1; i++)         {             generateheappermutations(n - 1, s, slist);              if (n % 2 == 0)             {                 // swap positions of 2 characters                 var chararray = s.tochararray();                 var temp = chararray[i];                 chararray[i] = chararray[n - 1];                 chararray[n - 1] = temp;                 s = new string(chararray);             }             else             {                 var chararray = s.tochararray();                 var temp = chararray[0];                 chararray[0] = chararray[n - 1];                 chararray[n - 1] = temp;                 s = new string(chararray);             }         }          generateheappermutations(n - 1, s, slist);     } } 

the algorithm yield correct number of permutations (in case, six), permutations incorrect:

abc       bac       cba                bca       abc       bac 

i don't think i'm deviating pseudocode example of heap's algorithm on wikipedia, , i'm having hard time debugging due recursive nature of algorithm (pretty tricky conceptualize).

could offer insight problem be?

p.s. not homework, fun.

first things first: debugging. when dealing recursion, easiest way debug code set break points in ide , step through bit bit, taking notes code behaving how expect to. allows @ values of variables @ every step.

you'll find passing string in everywhere not yielding expect because you're passing copy of instead of actual value. if pass reference instead (not sure if c# allows that), you'll you're expecting.


Comments