fork download
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5.  
  6. public class Test
  7. {
  8. enum Player
  9. {
  10. None = -1,
  11. FirstPlayer = 0,
  12. SecondPlayer = 1
  13. };
  14.  
  15. public static bool CheckWin(int n, IEnumerable<int> coinSequence)
  16. {
  17. if (coinSequence == null || coinSequence.Count() != 2 * n)
  18. throw new ArgumentException("coinSequence size must be equal 2*n");
  19.  
  20. var forcePlayer = Player.None;
  21. var currentPlayer = Player.None;
  22.  
  23. var playerCoins = new int[2] { n, 0 };
  24. var playerMoved = new int[2] { 0, 0 };
  25. var coinsOnDesk = 0;
  26.  
  27. foreach (var coin in coinSequence)
  28. {
  29. currentPlayer = (Player)(coin == 1 ? 0 : 1);
  30.  
  31. // force player
  32. {
  33. if (playerMoved[(int)currentPlayer] > n)
  34. {
  35. switch (currentPlayer)
  36. {
  37. case Player.FirstPlayer: forcePlayer = Player.SecondPlayer; break;
  38. case Player.SecondPlayer: forcePlayer = Player.FirstPlayer; break;
  39. default: throw new Exception("Alg fail"); break;
  40. }
  41. }
  42.  
  43. if (forcePlayer != Player.None)
  44. currentPlayer = forcePlayer;
  45. }
  46.  
  47. switch (currentPlayer)
  48. {
  49. case Player.FirstPlayer:
  50. if (playerCoins[0] != 0)
  51. {
  52. playerCoins[0]--;
  53. coinsOnDesk++;
  54. }
  55. break;
  56. case Player.SecondPlayer:
  57. if (coinsOnDesk != 0)
  58. {
  59. coinsOnDesk--;
  60. playerCoins[1]++;
  61. }
  62. break;
  63. default: throw new Exception("Alg fail"); break;
  64. }
  65.  
  66. playerMoved[(int)currentPlayer]++;
  67. }
  68.  
  69. return (playerCoins[1] == n);
  70. }
  71.  
  72. public static IEnumerable<IEnumerable<int>> GenerateCoins(int n)
  73. {
  74. if (n == 1)
  75. {
  76. yield return new int[] { 1 };
  77. yield return new int[] { 2 };
  78. yield break;
  79. }
  80.  
  81. var smallerVariants = GenerateCoins(n - 1);
  82. foreach (var smallerVariant in smallerVariants)
  83. {
  84. yield return smallerVariant.Concat(new int[] { 1 });
  85. yield return smallerVariant.Concat(new int[] { 2 });
  86. }
  87.  
  88. yield break;
  89. }
  90.  
  91. public static int CountWinsSequences(int n)
  92. {
  93. return GenerateCoins(2 * n).Count(coinSequence => CheckWin(n, coinSequence));
  94. }
  95.  
  96. public static void Main()
  97. {
  98. for (int n = 1; n <= 5; n++)
  99. {
  100. Console.WriteLine("n = {0}, wins = {1}", n, CountWinsSequences(n));
  101. }
  102. }
  103. }
Success #stdin #stdout 0.05s 34192KB
stdin
Standard input is empty
stdout
n = 1, wins = 1
n = 2, wins = 2
n = 3, wins = 5
n = 4, wins = 14
n = 5, wins = 42