-
using System;
-
using System.Collections.Generic;
-
using System.Text;
-
namespace Combination
-
{
-
public class Combination
-
{
-
private int m_n = 0;
-
private int m_r = 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 R
-
{
-
get { return m_r; }
-
set
-
{
-
if (value < this.N )
-
{
-
m_r = value;
-
}
-
else
-
{
-
m_r = 1;
-
}
-
}
-
}
-
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 Combination( int n, int r)
-
{
-
this.N = n;
-
this.R = r;
-
this.TotalNum = factorial( this.N )/(factorial( this.N - this.R )*factorial( this.R ) );
-
this.LeftNum = this.TotalNum;
-
sString =
new int [ this.
R ];
-
reset( ref sString);
-
}
-
// Are there more combination?
-
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;
-
}
-
}
-
// Generate next combination
-
public int [ ] getNext( )
-
{
-
int i = this.R - 1;
-
if ( this.LeftNum == this.TotalNum )
-
{
-
this.LeftNum -= 1;
-
return sString;
-
}
-
while (sString[i] == this.N - this.R + i)
-
{
-
i--;
-
}
-
sString[i] += 1;
-
for ( int j = i + 1; j < this.R; j++)
-
{
-
sString[j] = sString[i] + j - i;
-
}
-
this.LeftNum -= 1;
-
return sString;
-
}
-
}
-
internal class Program
-
{
-
private static void Main( string [ ] args)
-
{
-
Console.Write ( "Please input set: " );
-
string [ ] sign = Console.ReadLine ( ).Split ( ' ' );
-
// Get r value
-
Console.Write ( "How many numbers do you select: " );
-
int rValue;
-
if ( int.TryParse (Console.ReadLine ( ), out rValue) == false )
-
{
-
rValue = 1;
-
}
-
Combination c =
new Combination
(sign.
Length, rValue
);
-
int [ ] indices;
-
List<string> output =
new List<string>
( );
-
// Generate all combination
-
while (c.hasMore ( ) )
-
{
-
StringBuilder sb =
new StringBuilder
( );
-
indices = c.getNext ( );
-
for ( int i = 0; i < indices.Length; i++)
-
{
-
sb.Append (sign[indices[i] ] );
-
}
-
output.Add (sb.ToString ( ) );
-
}
-
// List all combination
-
Console.Write ( "Combination: \n" );
-
output.Sort ( );
-
foreach ( string s in output)
-
{
-
Console.WriteLine (s);
-
}
-
Console.WriteLine ( "\npress any key to exit" );
-
Console.Read ( );
-
}
-
}
-
}