用C程式設計的一種改進的Nim遊戲?


修改後的Nim遊戲是一個最佳化陣列遊戲。此遊戲根據起始玩家和最佳移動來預測獲勝者。

遊戲邏輯−在此遊戲中,我們給定了一個數組{},其中包含元素。通常有兩個玩家玩遊戲,分別是player1和player2。雙方的目標都是確保從陣列中刪除所有數字。現在,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

更新於: 2019 年 8 月 7 日

539 次瀏覽

開啟你的 職業

完成課程,獲得證書

開始
廣告
© . All rights reserved.