Predict the winner in Coin Game
There are two players P1 and P2 and two piles of coins consisting of M and N coins respectively. At each turn, a player can choose only one of the piles out of these and discard the other one. This discarded pile cannot be used further in the game. The pile player chooses is further divided into two piles of non zero parts. The player who cannot divide the pile i.e. the number of coins in the pile is < 2, loses the game. The task is to determine which player wins if P1 starts the game and both the players play optimally.
Input: M = 4, N = 4
Output: Player 1
Player 1 can choose any one of the piles as both contain the same number of coins
and then splits the chosen one (the one which is not chosen is discarded) into two piles with 1 coin each.
Now, player 2 is left with no move (as both the remaining piles contain a single coin each
which cannot be split into two groups of non-zero coins).
Input: M = 1, N = 1
Output: Player 2
There’s no move to make.
Approach: Simply check if any of the pile consists of even number of coins. If yes then Player 1 wins else Player 2 wins.
Below is the implementation of the above approach:
Attention reader! Don’t stop learning now. Participate in the Scholorship Test for First-Step-to-DSA Course for Class 9 to 12 students.