非常偷懶的寫法,先產生 C(n, r) 的 Combination 集合 C,再將集合 C 中的子集合,作 Permutation 即可。
產生 Combination 參考【C# - 產生 Combination - C(n, r) 組合問題】;產生 Permutation 參考【C# - 產生 Permutation - P(n) 排列問題】。
程式碼:
-
using System;
-
using System.Collections.Generic;
-
using System.Text;
-
namespace PermutationNR
-
{
-
internal class Program
-
{
-
// from string to String[]: "abc" => {"a", "b", "c"}
-
public static string [ ] stringToStringArray( string source)
-
{
-
char [ ] temp = source.ToCharArray ( );
-
string [ ] target = new string [temp. Length ];
-
for ( int i = 0; i < temp.Length; i++)
-
{
-
target[i] = temp[i].ToString ( );
-
}
-
return target;
-
}
-
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> combinationSet = 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] ] );
-
}
-
combinationSet.Add (sb.ToString ( ) );
-
}
-
List<string> output = new List<string> ( );
-
foreach ( string s in combinationSet)
-
{
-
sign = stringToStringArray(s);
-
Permutation p = new Permutation (sign. Length );
-
// 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 ( "Permutaion: \n" );
-
output.Sort ( );
-
foreach ( string s in output)
-
{
-
Console.WriteLine (s);
-
}
-
Console.WriteLine ( "\npress any key to exit" );
-
Console.Read ( );
-
}
-
}
-
}
|