C# - P(n, r) 排列組合問題

C# - P(n, r) 排列組合問題

PermutationNR

非常偷懶的寫法,先產生 C(n, r) 的 Combination 集合 C,再將集合 C 中的子集合,作 Permutation 即可。

產生 Combination 參考【C# - 產生 Combination - C(n, r) 組合問題】;產生 Permutation 參考【C# - 產生 Permutation - P(n) 排列問題】。

程式碼:

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4. namespace PermutationNR
  5. {
  6. internal class Program
  7. {
  8. // from string to String[]: "abc" => {"a", "b", "c"}
  9. public static string [ ] stringToStringArray( string source)
  10. {
  11. char [ ] temp = source.ToCharArray ( );
  12. string [ ] target = new string [temp.Length ];
  13. for ( int i = 0; i < temp.Length; i++)
  14. {
  15. target[i] = temp[i].ToString ( );
  16. }
  17. return target;
  18. }
  19. private static void Main( string [ ] args)
  20. {
  21. Console.Write ( "Please input set: " );
  22. string [ ] sign = Console.ReadLine ( ).Split ( ' ' );
  23. // Get r value
  24. Console.Write ( "How many numbers do you select: " );
  25. int rValue;
  26. if ( int.TryParse (Console.ReadLine ( ), out rValue) == false )
  27. {
  28. rValue = 1;
  29. }
  30. Combination c = new Combination(sign.Length, rValue);
  31. int [ ] indices;
  32. List<string> combinationSet = new List<string>( );
  33. // Generate all combination
  34. while (c.hasMore ( ) )
  35. {
  36. StringBuilder sb = new StringBuilder( );
  37. indices = c.getNext ( );
  38. for ( int i = 0; i < indices.Length; i++)
  39. {
  40. sb.Append (sign[indices[i] ] );
  41. }
  42. combinationSet.Add (sb.ToString ( ) );
  43. }
  44. List<string> output = new List<string>( );
  45. foreach ( string s in combinationSet)
  46. {
  47. sign = stringToStringArray(s);
  48. Permutation p = new Permutation(sign.Length );
  49. // Generate all permutation
  50. while (p.hasMore ( ) )
  51. {
  52. StringBuilder sb = new StringBuilder( );
  53. indices = p.getNext ( );
  54. for ( int i = 0; i < indices.Length; i++)
  55. {
  56. sb.Append (sign[indices[i] ] );
  57. }
  58. output.Add (sb.ToString ( ) );
  59. }
  60. }
  61. // List all permutation
  62. Console.Write ( "Permutaion: \n" );
  63. output.Sort ( );
  64. foreach ( string s in output)
  65. {
  66. Console.WriteLine (s);
  67. }
  68. Console.WriteLine ( "\npress any key to exit" );
  69. Console.Read ( );
  70. }
  71. }
  72. }