Nim在C中的改进游戏?

Nim的改良游戏是数组的优化游戏。该游戏根据起始玩家和最佳动作来预测获胜者。

游戏逻辑-在此游戏中,我们获得了一个包含元素的数组{}。通常有两个玩家分别玩玩家1和玩家2。两者的目的都是确保从数组中删除所有数字。现在,player1必须删除所有可以被3整除的数字,而player2必须删除所有可以被5整除的数字。目的是确保它们以最佳方式删除所有元素并在这种情况下找到赢家。

示例

Array : {1,5, 75,2,65,7,25,6}
Winner : playerB.
A removes 75 -> B removes 5 -> A removes 6 -> B removes 65 -> No moves for A, B wins.

代码预览

该代码将找到A可以删除的元素数量,B可以删除的元素数量以及它们都可以删除的元素数量。基于它们都可以删除的元素数量,找到了解决方案。当A删除第一个元素时,即使他必须比B删除一个元素,它也可以获胜。在正常情况下,拥有最大元素数才能删除的玩家获胜。

寻找NIM游戏解决方案的程序

#include <bits/stdc++.h>
using namespace std;
int main() {
   int arr[] = {1,5, 75,2,65,7,25,6};
   int n = sizeof(arr) / sizeof(arr[0]);
   int movesA = 0, movesB = 0, movesBoth = 0;
   for (int i = 0; i < n; i++) {
      if (arr[i] % 3 == 0 && arr[i] % 5 == 0)
         movesBoth++;
      else if (arr[i] % 3 == 0)
         movesA++;
      else if (arr[i] % 5 == 0)
         movesB++;
   }
   if (movesBoth == 0) {
      if (movesA > movesB)
         cout<<"Player 1 is the Winner";
      cout<<"Player 2 is the Winner";
   }
   if (movesA + 1 > movesB)
      cout<<"Player 1 is the Winner";
   cout<<"Player 2 is the Winner"; ;
   return 0;
}

输出结果

Player 2 is the Winner