首页  >  文章  >  后端开发  >  一个用C语言修改过的Nim游戏?

一个用C语言修改过的Nim游戏?

PHPz
PHPz转载
2023-09-01 14:57:07706浏览

一个用C语言修改过的Nim游戏?

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

游戏逻辑 - 在这个游戏中,我们得到一个包含元素的数组{}。通常有两个玩家玩游戏,即玩家 1 和玩家 2。两者的目的都是确保从数组中删除它们的所有数字。现在,玩家 1 必须删除所有可被 3 整除的数字,玩家 2 必须删除所有可被 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;
}

输出

rree

以上是一个用C语言修改过的Nim游戏?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文转载于:tutorialspoint.com。如有侵权,请联系admin@php.cn删除