Software & Finance Forums

### Author Topic: Permutation Algorithm in C#  (Read 1144 times)

#### kathir

• Sr. Member
• Posts: 283
##### Permutation Algorithm in C#
« on: June 08, 2011, 04:12:05 am »
I have implemented permutation algorithm on Turbo C, Visual C++, C# and Java.

Turbo C/C++ programmers: http://www.softwareandfinance.com/Turbo_CPP/MRP.html

Visual C++ programmers: http://www.softwareandfinance.com/Visual_CPP/MRP.html

C# programmers: http://www.softwareandfinance.com/CSharp/MRP.html

Java programmers: http://www.softwareandfinance.com/Java/MRP.html

Make sure you like us on http://facebook.softwareandfinance.com to serve you better.

using System;

using System.Collections.Generic;

using System.Text;

namespace CSPermutation

{

class Program

{

static public void sortchar(char [] buffer, int len)

{

for (int i = 1; i < len; i++)

{

for (int j = 0; j < len - i; j++)

{

if (buffer[j] > buffer[j + 1])

{

char temp = buffer[j];

buffer[j] = buffer[j + 1];

buffer[j + 1] = temp;

}

}

}

}

static public bool NextPermuation(char[] p, int len)

{

for(int k = len - 1; k > 0; k--)

{

if(p[k - 1] >= p[k])

continue;

else

{

if(k <= len - 3)

{

char newchar = p[k-1];

int anchor = -1;

for(int j = len - 1; j >= k; j--)

{

if(newchar < p[j])

{

anchor = j;

break;

}

}

if(anchor == -1)

return false;

char ch = p[k-1];

p[k-1] = p[anchor];

p[anchor] = ch;

char[] tbuffer = new char[len - k];

for (int m = 0; m < len - k; m++)

tbuffer[m] = p[k + m];

sortchar(tbuffer, len - k);

for (int n = 0; n < len - k; n++)

p[k + n] = tbuffer[n];

return true;

}

else

{

char[] tempptr = new char[3];

tempptr[0] = p[p.Length - 3];

tempptr[1] = p[p.Length - 2];

tempptr[2] = p[p.Length - 1];

int count = 3;

for(int i = count - 1; i > 0; i--)

{

if(tempptr[i - 1] >= tempptr)

continue;

else

{

if(i <= count - 2)

{

if(tempptr[i+1] > tempptr[i-1])

{

char ch = tempptr[i+1];

tempptr[i+1] = tempptr;

tempptr = tempptr[i-1];

tempptr[i-1] = ch;

}

else

{

char ch = tempptr[i-1];

tempptr[i-1] = tempptr;

tempptr = tempptr[i+1];

tempptr[i+1] = ch;

}

}

else

{

char ch = tempptr;

tempptr = tempptr[i-1];

tempptr[i-1] = ch;

}

p[p.Length - 3] = tempptr[0];

p[p.Length - 2] = tempptr[1];

p[p.Length - 1] = tempptr[2];

return true;

}

}

return false;

}

}

}

return false;

}

static void Main(string[] args)

{

Console.WriteLine("Enter a string to find permutation:");

char[] buffer = s.ToCharArray();

// sortchar(buffer, buffer.Length); // use it only if you require

int count = 0;

while(true)

{

Console.WriteLine(buffer);

count++;

if (NextPermuation(buffer, buffer.Length) == false)

break;

}

Console.WriteLine("\nCount: " + count);

}

}

}

Disclaimer: This web site is for educational and informational purposes only. Click here to read the Disclaimer.