Skip to content
Related Articles

Related Articles

Improve Article
Find the winner in nim-game
  • Difficulty Level : Hard
  • Last Updated : 06 Apr, 2021

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 looses. This problem is variation of nim-game. 
Note : Each players play game alternately. Find out winner if both of the players play optimally. Alice starts the game first. In case 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. 
 

  1. XOR of array is already 0: In this case Alice will unable to make a move and hence Alice is winner.
  2. 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.

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++




// CPP to find nim-game winner
#include <bits/stdc++.h>
using namespace std;
 
// function to find winner of NIM-game
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 program
int main()
{
    int A[] = { 1, 4, 3, 5 };
    int n = siseof(A) / sizeof(A[0]);
    cout << "Winner = " << findWinner(A, n);
    return 0;
}

Java




// Java to find nim-game winner
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 (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




# Python3 program to find nim-game winner
 
# Function to find winner of NIM-game
def 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 code
A = [ 1, 4, 3, 5 ]
n = len(A)
print("Winner = ", findWinner(A, n))
 
# This code is contributed by Anant Agarwal.

C#




// C# to find nim-game winner
using 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
// PHP to find nim-game winner
 
// function to find
// winner of NIM-game
function 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.
?>

Javascript




<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

 

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with industry experts, please refer DSA Live Classes




My Personal Notes arrow_drop_up
Recommended Articles
Page :