-
using System;
-
using System.Collections.Generic;
-
using System.Text;
-
namespace Permutation
-
{
-
internal class Permutation
-
{
-
private int m_n = 0;
-
private int m_totalNum = 0;
-
private int m_leftNum = 0;
-
private int [ ] sString;
-
public int N
-
{
-
get { return m_n; }
-
set { m_n = value; }
-
}
-
public int TotalNum
-
{
-
get { return m_totalNum; }
-
set { m_totalNum = value; }
-
}
-
public int LeftNum
-
{
-
get { return m_leftNum; }
-
set { m_leftNum = value; }
-
}
-
// calcualte n!
-
public int factorial( int n)
-
{
-
int result = 1;
-
for ( int i = n; i >= 1; i--)
-
{
-
result *= i;
-
}
-
return result;
-
}
-
// Constructor
-
public Permutation( int n)
-
{
-
this.N = n;
-
this.TotalNum = factorial( this.N );
-
this.LeftNum = this.TotalNum;
-
sString =
new int [ this.
N ];
-
reset( ref sString);
-
}
-
// Are there more permutation?
-
public bool hasMore( )
-
{
-
return ( this.LeftNum == 0 ) ? false : true;
-
}
-
// Reset
-
public void reset( ref int [ ] sString)
-
{
-
for ( int i = 0; i < sString.Length; i++)
-
{
-
sString[i] = i;
-
}
-
}
-
// Swap two value => (a, b) = (b, a)
-
public void swap( ref int a, ref int b)
-
{
-
a ^= b;
-
b ^= a;
-
a ^= b;
-
}
-
// Generate next permutation
-
public int [ ] getNext( )
-
{
-
if ( this.LeftNum == this.TotalNum )
-
{
-
this.LeftNum -= 1;
-
return sString;
-
}
-
-
int i = sString.Length - 2;
-
while (sString[i] > sString[i + 1 ] )
-
{
-
i--;
-
}
-
-
int j = sString.Length - 1;
-
while (sString[i] > sString[j] )
-
{
-
j--;
-
}
-
swap( ref sString[i], ref sString[j] );
-
int x = sString.Length - 1;
-
int y = i + 1;
-
while (x > y)
-
{
-
swap( ref sString[x], ref sString[y] );
-
x--;
-
y++;
-
}
-
this.LeftNum -= 1;
-
return sString;
-
}
-
}
-
internal class Program
-
{
-
private static void Main( string [ ] args)
-
{
-
Console.Write ( "Please input set: " );
-
string [ ] sign = Console.ReadLine ( ).Split ( ' ' );
-
Permutation p =
new Permutation
(sign.
Length );
-
int [ ] indices;
-
List<string> output =
new List<string>
( );
-
// Generate all permutation
-
while (p.hasMore ( ) )
-
{
-
StringBuilder sb =
new StringBuilder
( );
-
indices = p.getNext ( );
-
for ( int i = 0; i < indices.Length; i++)
-
{
-
sb.Append (sign[indices[i] ] );
-
}
-
output.Add (sb.ToString ( ) );
-
}
-
// List all permutation
-
Console.Write ( "Permutation: \n" );
-
output.Sort ( );
-
foreach ( string s in output)
-
{
-
Console.WriteLine (s);
-
}
-
Console.WriteLine ( "\npress any key to exit" );
-
Console.Read ( );
-
}
-
}
-
}