# Predict the winner of the game on the basis of the absolute difference of sum by selecting numbers in C++

In this problem, we are given an array of n numbers. And there are two players X and Y. Our task is to predict the winner of the game.

For player X to win the absolute difference of the sum of numbers by X and Y should be a multiple of 4. If it is not divisible by 4, then Y wins. Player X starts the game.

Let’s take an example to understand the problem,

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.

To solve this problem, we will check if every element of the array is divisible by 4 and keep track on the remainder found when we divide a number by 4. If the occurrence of every remainder is even, then X wins. i.e. the absolute difference is divisible by 4.

Count of arr[i]%4 for every value 0, 1, 2 ,3 should be even.

Program to show the implementation of our algorithm,

## Example

Live Demo

#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;
}

## Output

Game Started!
X wins the Game

Advertisements