基於C++選擇數字計算絕對差值來預測遊戲獲勝者


在這個問題中,我們得到一個包含n個數字的陣列。有兩個玩家X和Y。我們的任務是預測遊戲的獲勝者。

對於玩家X獲勝,玩家X和Y選擇的數字之和的絕對差值必須是4的倍數。如果不是4的倍數,則Y獲勝。玩家X先開始遊戲。

讓我們舉個例子來理解這個問題:

Input: a[] = {3 6 9 12}
Output: X
Explaination:
X selects 3 and 6
Y selects 12 and 9
|3+6 - 12+9| = 12, 12 is a multiple of 4.

為了解決這個問題,我們將檢查陣列的每個元素是否能被4整除,並跟蹤將數字除以4後得到的餘數。如果每個餘數的出現次數都是偶數,則X獲勝,即絕對差值可以被4整除。

對於每個值0、1、2、3,arr[i]%4的計數應該都是偶數。

展示我們演算法實現的程式:

示例

 線上演示

#include <iostream>
using namespace std;
int playGame(int a[], int n) {
   int count[4] = {0,0,0,0};
   for (int i = 0; i < n; i++) {
      for(int j = 0; j<4;j++){
         if(a[i]%4 == j)
            count[j]++;
      }
   }
   if (count[0] % 2 == 0 && count[1] % 2 == 0 && count[2] % 2 == 0 && count[3] == 0)
      return 1;
   else
      return 2;
}
int main() {
   int a[] = { 4, 8, 5, 9 };
   int n = sizeof(a) / sizeof(a[0]);
   cout<<"Game Started!\n";
   if (playGame(a, n) == 1)
      cout << "X wins the Game";
   else
      cout << "Y wins the Game";
   return 0;
}

輸出

Game Started!
X wins the Game

更新於:2020年2月4日

106 次瀏覽

開啟您的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.