通过选择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