Find the winner in nim-game

14 Jun, 2022
You are given an array A[] of n-elements. There are two players Alice and Bob. A Player can choose any of element from array and remove it. If the bitwise XOR of all remaining elements equals 0 after removal of selected element, then that player loses. This problem is variation of nim-game. 
Note: Each player play game alternately. Find out winner if both of the players play optimally. Alice starts the game first. In case one-element in array consider its value as the XOR of array. 
Examples :  
Input : A[] = {3, 3, 2} Output : Winner = Bob Explanation : Alice can select 2 and remove it that make XOR of array equals to zero also if Alice choose 3 to remove than Bob can choose any of 2/3 and finally Alice have to make his steps.
Input : A[] = {3, 3} Output : Winner = Alice Explanation : As XOR of array is already zero Alice can’t select any element to remove and hence Alice is winner.  
Let’s start the solution step by step. We have total of three option for the XOR of array and this game.  
XOR of array is already 0: In this case Alice will unable to make a move and hence Alice is winner.XOR of array is not zero: Now, in this case we have two options, either size of array will be odd or even.CASE A: If the array size is odd then for sure Bob will win the game.CASE B: If the array size is even then Alice will win the game.
XOR of array is already 0: In this case Alice will unable to make a move and hence Alice is winner.
XOR of array is not zero: Now, in this case we have two options, either size of array will be odd or even.CASE A: If the array size is odd then for sure Bob will win the game.CASE B: If the array size is even then Alice will win the game.
CASE A: If the array size is odd then for sure Bob will win the game.
CASE B: If the array size is even then Alice will win the game.
Above conclusion can be proved with the help of mathematical induction.Let A[] = {1} i.e. size of array is odd and XOR of array is non-zero: In this case Alice can select element 1 and then A[] will become empty and hence XOR of array can be considered as zero. Resulting Bob as winner.Let size of array is even and XOR of array is non-zero. Now we can prove that Alice can always find an element to remove such that XOR of remaining elements of array will be non-zero. 
To prove this lets start from the contradiction i.e. suppose whatever element you should choose XOR of remaining array must be zero. So, let A1 Xor A2 Xor ... An = X and n is even. As per our contradiction hypothesis, Ai Xor X = 0 for 1<= i <= n. Calculate XOR of all X Xor Ai (i.e. n equations), After taking XOR of all n equations we have X Xor X...Xor X (n-times) = 0 as N is even. Now, also we have A1 Xor A2 Xor.. An = 0 but we know A1 Xor A2...Xor = X. This means we have at least one element in even-size array such that after its removal XOR of remaining elements in non-zero.
Let size of array is even and XOR of array is non-zero. Alice can not remove an element Ai such that xor of remaining number is zero, because that will make Bob win. Now, take the other case when the xor of remaining N?1 number is non-zero. As we know that N?1 is even and from the induction hypothesis, we can say that the position after the current move will be a winning position for Bob. Hence, it is a losing position for Alice.
int res = 0;
for (int i = 1; i <= N; i++) {
    res ^= a[i];
}

if (res == 0)
    return "ALice";
if (N%2 == 0)
    return "Alice";
else
    return "Bob";
C++
Java
Python3
C#
PHP
Javascript
// CPP to find nim-game winner#include <bits/stdc++.h>using namespace std; // function to find winner of NIM-gamestring findWinner(int A[], int n){    int res = 0;    for (int i = 0; i < n; i++)        res ^= A[i];     // case when Alice is winner    if (res == 0 || n % 2 == 0)        return "Alice";     // when Bob is winner    else        return "Bob";} // driver programint main(){    int A[] = { 1, 4, 3, 5 };    int n = sizeof(A) / sizeof(A[0]);    cout << "Winner = " << findWinner(A, n);    return 0;}
// Java to find nim-game winnerclass GFG {         // function to find winner of NIM-game    static String findWinner(int A[], int n)    {        int res = 0;                 for (int i = 0; i < n; i++)            res ^= A[i];             // case when Alice is winner        if (res == 0 || n % 2 == 0)            return "Alice";             // when Bob is winner        else            return "Bob";    }         //Driver code    public static void main (String[] args)    {        int A[] = { 1, 4, 3, 5 };        int n =A.length;                 System.out.print("Winner = "                    + findWinner(A, n));    }} // This code is contributed by Anant Agarwal.
# Python3 program to find nim-game winner # Function to find winner of NIM-gamedef findWinner(A, n):     res = 0    for i in range(n):        res ^= A[i]     # case when Alice is winner    if (res == 0 or n % 2 == 0):        return "Alice"     # when Bob is winner    else:        return "Bob" # Driver codeA = [ 1, 4, 3, 5 ]n = len(A)print("Winner = ", findWinner(A, n)) # This code is contributed by Anant Agarwal.
// C# to find nim-game winnerusing System; class GFG {         // function to find winner of NIM-game    static String findWinner(int []A, int n)    {        int res = 0;                 for (int i = 0; i < n; i++)            res ^= A[i];             // case when Alice is winner        if (res == 0 || n % 2 == 0)            return "Alice";             // when Bob is winner        else            return "Bob";    }         //Driver code    public static void Main ()    {        int []A = { 1, 4, 3, 5 };        int n =A.Length;                 Console.WriteLine("Winner = "                    + findWinner(A, n));    }} // This code is contributed by vt_m.
<?php// PHP to find nim-game winner // function to find// winner of NIM-gamefunction findWinner($A, $n){    $res = 0;    for ($i = 0; $i < $n; $i++)        $res ^= $A[$i];     // case when Alice is winner    if ($res == 0 or $n % 2 == 0)        return "Alice";     // when Bob is winner    else        return "Bob";} // Driver Code$A = array(1, 4, 3, 5 );$n = count($A);echo "Winner = " , findWinner($A, $n); // This code is contributed by vt_m.?>
<script> // JavaScript program to find nim-game winner     // function to find winner of NIM-game    function findWinner(A, n)    {        let res = 0;                   for (let i = 0; i < n; i++)            res ^= A[i];               // case when Alice is winner        if (res == 0 || n % 2 == 0)            return "Alice";               // when Bob is winner        else            return "Bob";    }  // Driver Code         let A = [ 1, 4, 3, 5 ];        let n = A.length;                   document.write("Winner = "                    + findWinner(A, n));   </script>
Output : 
Winner = Alice
Time Complexity : O(N)  Where N is the given size of the array. As we are traversing the array in a single for loop for N elements. Hence time complexity is O(N).
Auxiliary Space : O( 1 ) as we are not utilizing any extra space in memory so space needed is constant
vt_m
avijitmondal1998
arorakashish0911
SauravKumarGupta
simmytarika5
devendrasalunke
Bitwise-XOR
Bit Magic
Game Theory
Bit Magic
Game Theory
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Divide two integers without using multiplication, division and mod operator
Bit Fields in C
Set, Clear and Toggle a given bit of a number in C
Find the two non-repeating elements in an array of repeating elements/ Unique Numbers 2
Count total set bits in all numbers from 1 to n
Implementation of Tic-Tac-Toe game
Minimax Algorithm in Game Theory | Set 2 (Introduction to Evaluation Function)
Card Shuffle Problem | TCS Digital Advanced Coding Question
Chessboard Pawn-Pawn game
Expectimax Algorithm in Game Theory