- Related Questions & Answers
- Average numbers in array in C Programming
- C Program to Multiply two Floating Point Numbers?
- Sum of the numbers up to N that are divisible by 2 or 5 in c programming
- Sum of first n natural numbers in C Program
- Sum of squares of first n natural numbers in C Program?
- Sum of squares of the first n even numbers in C Program
- A modified game of Nim in C ?
- What is the difference between Enumeration interface and enum in Java?
- Find all the numbers in a string using regular expression in Python
- Lambda expression in Python to rearrange positive and negative numbers
- Absolute and Relative frequency in Pandas
- Absolute Deviation and Absolute Mean Deviation using NumPy
- What is the difference between throw e and throw new Exception(e) in catch block in java?
- What is the difference between selenium and automation?
- What is difference between selenium 1 and Selenium 2

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

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,

#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

Advertisements