C# Crawler
Sagiv Hadaya is crawling in C#...just for fun




 

Permutations

This was a Weblog note, but i have decided to include that as a sample of easy usage of C# to create a nice function.

(this is being asked in many interviews, and its nice to see how its easily done in C#).

The Function takes a string of characters, and writes down every possible permutation of that exact string, so for exaple, if "ABC" has been supplied, should spill out:

ABC, ACB, BAC, BCA, CAB, CBA.

using System;

namespace ConsoleApplication3

{

        class Permute

        {

                 private void swap (ref char a, ref char b)

                 {

                        if(a==b)return;

                        a^=b;

                        b^=a;

                        a^=b;

                  }

                  public void setper(char[] list)

                  {

                        int x=list.Length-1;

                        go(list,0,x);

                  }

                  private void go (char[] list, int k, int m)

                  {

                        int i;

                        if (k == m)

                           {

                                 Console.Write (list);

                                 Console.WriteLine (" ");

                            }

                        else

                             for (i = k; i <= m; i++)

                            {

                                   swap (ref list[k],ref list[i]);

                                   go (list, k+1, m);

                                   swap (ref list[k],ref list[i]);

                             }

                   }

         }

         class Class1

        {

               static void Main()

               {

                      Permute p = new Permute();

                      string c="sagiv";

                       char []c2=c.ToCharArray ();

                       /*calling the permute*/

                      p.setper(c2);

                  }

           }

}


Click here to visit the Radio UserLand website.
Click to see the XML version of this web page.
Click here to send an email to the editor of this weblog.
© Copyright 2002 Sagiv Hadaya.
Last update: 10/14/2002; 12:47:54 AM.