C++ program to find winner of ball removal game

C++Server Side ProgrammingProgramming

Suppose we have four numbers n1, n2, k1 and k2. Consider there are 2 boxes, first one has n1 balls and second one has n2 balls. Amal and Bimal are playing the game. In one move they can take from 1 to k1 balls and throw them out, similarly second one will take 1 to k2 balls in his move. Amal starts the game and they plays alternatively. The one who cannot play his move will lose the game. We have to find who will be the winner.

So, if the input is like n1 = 2; n2 = 2; k1 = 1; k2 = 2, then the output will be Bimal, because each box has 2 balls. Amal takes single ball from first box and then Bimal can take either 1 or 2 balls from the second box. No matter how Amal acts, Bimal can always win if he plays optimally.

Steps

To solve this, we will follow these steps −

if n1 > n2, then:
   return "Amal"
Otherwise
   return "Biaml"

Example

Let us see the following implementation to get better understanding −

#include <bits/stdc++.h>
using namespace std;

string solve(int n1, int n2, int k1, int k2) {
   if (n1 > n2)
      return "Amal";
   else
      return "Biaml";
}
int main() {
   int n1 = 2;
   int n2 = 2;
   int k1 = 1;
   int k2 = 2;
   cout << solve(n1, n2, k1, k2) << endl;
}

Input

2, 2, 1, 2

Output

Biaml
raja
Updated on 04-Mar-2022 09:54:30

Advertisements