Find the winner of a game of removing any number of stones from the least indexed non-empty pile from given N piles - GeeksforGeeks

17 Jun, 2021
Given an array arr[] consisting of N integers, each representing size of a pile of stones. The task is to determine the winner of the game when two players, A and B, play a game optimally as per the following conditions:
Player A always starts the game.
In one move, a player may remove any number of stones (at least 1), from the first non-empty pile with minimal index.
The first player who cannot make a move loses the game.
Print “A” if player A wins the game. Otherwise, print “B”.
Examples:
Input: arr[] = {1, 1, 1, 1, 1, 1}Output: BExplanation:Here, each pile has only one stone so A and B will alternatively remove one stone each.A removes 1 stone from 1st pile, B removes 1 from 2nd pile and so on.Last stone in 6th pile is removed by B.Since A has no choice left, B wins the game.
Input: arr[] = {1, 1, 2, 1}Output: AExplanation:Here, A removes 1 stone from 1st pile, B removes 1 from 2nd pile, A removes only 1 from 3rd pile, and now B is forced to remove 1 from 3rd pile. Last stone in 4th pile is removed by A.Since B has no choice left, A wins the game.
Approach: The idea is to figure out the optimal ways that players should follow to win the game. Below are two ways to play optimally:
For all piles except the last one, if there are K stones on a pile then the current player will pick only (K – 1) stones (only if K > 1) so that another player is forced to pick the remaining 1 stone. This guarantees the current player to get a chance to pick stones from the next pile and eventually win.
For the last pile, if it has K stones, then all K stones will be picked by the current player so that the other player does not get a chance to pick stones. This eventually guarantees the current player to win.
Follow the steps below to solve this problem:
Initially, assuming that the player will remove all stones from the current pile, A will be the winner if the size of the array is odd and B if the size is even.Now, iterate over the range [0, N – 2] and check the current index and number of stones present on the current pile to decide which player will win.While traversing, if the index is even, A will get a chance to pick a stone. Otherwise, B will get a chance to pick stones.If the current index is even and the number of stones is greater than 1, then the winner is set to B. Update winner to A.If the current index is odd and the number of stones exceeds 1, the winner is set to be A. Then, update the winner to B.Finally, print the winner of the game.
Initially, assuming that the player will remove all stones from the current pile, A will be the winner if the size of the array is odd and B if the size is even.
Now, iterate over the range [0, N – 2] and check the current index and number of stones present on the current pile to decide which player will win.
While traversing, if the index is even, A will get a chance to pick a stone. Otherwise, B will get a chance to pick stones.
If the current index is even and the number of stones is greater than 1, then the winner is set to B. Update winner to A.
If the current index is odd and the number of stones exceeds 1, the winner is set to be A. Then, update the winner to B.
Finally, print the winner of the game.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program for the above approach #include <bits/stdc++.h>using namespace std; // Function to find the winner// of game between A and Bvoid findWinner(int a[], int n){    // win = 1 means B is winner    // win = 0 means A is winner    int win = 0;     // If size is even, winner is B    if (n % 2 == 0)        win = 1;     // If size is odd, winner is A    else        win = 0;     for (int i = n - 2; i >= 0; i--) {         // Stone will be removed by B        if (i % 2 == 1) {             // If B wants to win             // B will take n-1 stones            // from current pile having            // n stones and force A to            // pick 1 stone            if (win == 0 && a[i] > 1)                win = 1;        }         // Stone will be removed by A        else {             // If A wants to win             // A will take n-1 stones from            // current pile having n stones            // and force B to pick 1 stone            if (win == 1 && a[i] > 1)                win = 0;        }    }     // Print the winner accordingly    if (win == 0)        cout << "A";    else        cout << "B";} // Driver Codeint main(){    // Given piles of stone    int arr[] = { 1, 1, 1, 2 };     int N = sizeof(arr) / sizeof(arr[0]);     // Function Call    findWinner(arr, N);     return 0;}
// Java program for the above approachimport java.util.*; class GFG{ // Function to find the winner// of game between A and Bstatic void findWinner(int a[], int n){         // win = 1 means B is winner    // win = 0 means A is winner    int win = 0;     // If size is even, winner is B    if (n % 2 == 0)        win = 1;     // If size is odd, winner is A    else        win = 0;     for(int i = n - 2; i >= 0; i--)    {                 // Stone will be removed by B        if (i % 2 == 1)        {                         // If B wants to win             // B will take n-1 stones            // from current pile having            // n stones and force A to            // pick 1 stone            if (win == 0 && a[i] > 1)                win = 1;        }         // Stone will be removed by A        else        {                         // If A wants to win             // A will take n-1 stones from            // current pile having n stones            // and force B to pick 1 stone            if (win == 1 && a[i] > 1)                win = 0;        }    }     // Print the winner accordingly    if (win == 0)        System.out.print("A");    else        System.out.print("B");} // Driver Codepublic static void main(String[] args){         // Given piles of stone    int arr[] = { 1, 1, 1, 2 };     int N = arr.length;     // Function call    findWinner(arr, N);}} // This code is contributed by Amit Katiyar
# Python3 program for the above approach # Function to find the winner# of game between A and Bdef findWinner(a, n):         # win = 1 means B is winner    # win = 0 means A is winner    win = 0     # If size is even, winner is B    if (n % 2 == 0):        win = 1     # If size is odd, winner is A    else:        win = 0     for i in range(n - 2, -1, -1):         # Stone will be removed by B        if (i % 2 == 1):             # If B wants to win             # B will take n-1 stones            # from current pile having            # n stones and force A to            # pick 1 stone            if (win == 0 and a[i] > 1):                win = 1         # Stone will be removed by A        else:             # If A wants to win             # A will take n-1 stones from            # current pile having n stones            # and force B to pick 1 stone            if (win == 1 and a[i] > 1):                win = 0                     # Print the winner accordingly    if (win == 0):        print("A")    else:        print("B") # Driver Codeif __name__ == '__main__':         # Given piles of stone    arr = [ 1, 1, 1, 2 ]     N = len(arr)     # Function call    findWinner(arr, N) # This code is contributed by mohit kumar 29
// C# program for the// above approachusing System;class GFG{ // Function to find the winner// of game between A and Bstatic void findWinner(int []a,                       int n){     // win = 1 means B is winner  // win = 0 means A is winner  int win = 0;   // If size is even, winner is B  if (n % 2 == 0)    win = 1;   // If size is odd, winner is A  else    win = 0;   for(int i = n - 2; i >= 0; i--)  {    // Stone will be removed by B    if (i % 2 == 1)    {       // If B wants to win       // B will take n-1 stones      // from current pile having      // n stones and force A to      // pick 1 stone      if (win == 0 && a[i] > 1)        win = 1;    }     // Stone will be removed by A    else    {      // If A wants to win      // A will take n-1 stones from      // current pile having n stones      // and force B to pick 1 stone      if (win == 1 && a[i] > 1)        win = 0;    }  }   // Print the winner accordingly  if (win == 0)    Console.Write("A");  else    Console.Write("B");} // Driver Codepublic static void Main(String[] args){  // Given piles of stone  int []arr = {1, 1, 1, 2};   int N = arr.Length;   // Function call  findWinner(arr, N);}}  // This code is contributed by Rajput-Ji
<script>// Javascript program for the above approach // Function to find the winner// of game between A and Bfunction findWinner(a, n){     // win = 1 means B is winner    // win = 0 means A is winner    let win = 0;      // If size is even, winner is B    if (n % 2 == 0)        win = 1;      // If size is odd, winner is A    else        win = 0;      for(let i = n - 2; i >= 0; i--)    {                  // Stone will be removed by B        if (i % 2 == 1)        {                          // If B wants to win              // B will take n-1 stones            // from current pile having            // n stones and force A to            // pick 1 stone            if (win == 0 && a[i] > 1)                win = 1;        }          // Stone will be removed by A        else        {                          // If A wants to win              // A will take n-1 stones from            // current pile having n stones            // and force B to pick 1 stone            if (win == 1 && a[i] > 1)                win = 0;        }    }      // Print the winner accordingly    if (win == 0)        document.write("A");    else        document.write("B");} // Driver Code// Given piles of stonelet arr=[1, 1, 1, 2];let N = arr.length; // Function callfindWinner(arr, N); // This code is contributed by unknown2108</script>
B
Time Complexity: O(N)Auxiliary Space: O(1)
mohit kumar 29
amit143katiyar
Rajput-Ji
unknown2108
Arrays
Game Theory
Greedy
Arrays
Greedy
Game Theory
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Maximum and minimum of an array using minimum number of comparisons
Stack Data Structure (Introduction and Program)
Top 50 Array Coding Problems for Interviews
Multidimensional Arrays in Java
Introduction to Arrays
Implementation of Tic-Tac-Toe game
Expectimax Algorithm in Game Theory
Minimax Algorithm in Game Theory | Set 2 (Introduction to Evaluation Function)
Game Theory (Normal-form Game) | Set 4 (Dominance Property-Pure Strategy)
Game Theory (Normal-form game) | Set 3 (Game with Mixed Strategy)