The Wayback Machine - https://web.archive.org/web/20240920151052/https://www.geeksforgeeks.org/combinatorial-game-theory-set-2-game-nim/
Open In App

Combinatorial Game Theory | Set 2 (Game of Nim)

Last Updated : 23 Sep, 2022
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

We strongly recommend to refer below article as a prerequisite of this. Combinatorial Game Theory | Set 1 (Introduction) In this post, Game of Nim is discussed. The Game of Nim is described by the following rules- “ Given a number of piles in which each pile contains some numbers of stones/coins. In each turn, a player can choose only one pile and remove any number of stones (at least one) from that pile. The player who cannot move is considered to lose the game (i.e., one who take the last stone is the winner). ” For example, consider that there are two players- A and B, and initially there are three piles of coins initially having 3, 4, 5 coins in each of them as shown below. We assume that first move is made by A. See the below figure for clear understanding of the whole game play. Set2_Nim_Game_start_with_A A Won the match (Note: A made the first move) So was A having a strong expertise in this game ? or he/she was having some edge over B by starting first ? Let us now play again, with the same configuration of the piles as above but this time B starting first instead of A. gameofnim11 B Won the match (Note: B made the first move) By the above figure, it must be clear that the game depends on one important factor – Who starts the game first ? So does the player who starts first will win everytime ? Let us again play the game, starting from A , and this time with a different initial configuration of piles. The piles have 1, 4, 5 coins initially. Will A win again as he has started first ? Let us see. gameofnim4 A made the first move, but lost the Game. So, the result is clear. A has lost. But how? We know that this game depends heavily on which player starts first. Thus, there must be another factor which dominates the result of this simple-yet-interesting game. That factor is the initial configuration of the heaps/piles. This time the initial configuration was different from the previous one. So, we can conclude that this game depends on two factors-

  1. The player who starts first.
  2. The initial configuration of the piles/heaps.

In fact, we can predict the winner of the game before even playing the game ! Nim-Sum : The cumulative XOR value of the number of coins/stones in each piles/heaps at any point of the game is called Nim-Sum at that point. “If both A and B play optimally (i.e- they don’t make any mistakes), then the player starting first is guaranteed to win if the Nim-Sum at the beginning of the game is non-zero. Otherwise, if the Nim-Sum evaluates to zero, then player A will lose definitely.” For the proof of the above theorem, see- https://en.wikipedia.org/wiki/Nim#Proof_of_the_winning_formula

Optimal Strategy :

  • If the XOR sum of ‘n’ numbers is already zero then there is no possibility to make the XOR sum zero by single reduction of a number.
  • If the XOR sum of ‘n’ numbers is non-zero then there is at least a single approach by which if you reduce a number, the XOR sum is zero.

Initially two cases could exist. Case 1: Initial Nim Sum is zero As we know, in this case if played optimally B wins, which means B would always prefer to have Nim sum of zero for A‘s turn. So, as the Nim Sum is initially zero, whatever number of items A removes the new Nim Sum would be non-zero (as mentioned above). Also, as B would prefer Nim sum of zero for A‘s turn, he would then play a move so as to make the Nim Sum zero again (which is always possible, as mentioned above). The game will run as long as there are items in any of the piles and in each of their respective turns A would make Nim sum non-zero and B would make it zero again and eventually there will be no elements left and B being the one to pick the last wins the game. It is evident by above explanation that the optimal strategy for each player is to make the Nim Sum for his opponent zero in each of their turn, which will not be possible if it’s already zero. Case 2: Initial Nim Sum is non-zero Now going by the optimal approach A would make the Nim Sum to be zero now (which is possible as the initial Nim sum is non-zero, as mentioned above). Now, in B‘s turn as the nim sum is already zero whatever number B picks, the nim sum would be non-zero and A can pick a number to make the nim sum zero again. This will go as long as there are items available in any pile. And A will be the one to pick the last item. So, as discussed in the above cases, it should be obvious now that Optimal strategy for any player is to make the nim sum zero if it’s non-zero and if it is already zero then whatever moves the player makes now, it can be countered.

Let us apply the above theorem in the games played above. In the first game A started first and the Nim-Sum at the beginning of the game was, 3 XOR 4 XOR 5 = 2, which is a non-zero value, and hence A won. Whereas in the second game-play, when the initial configuration of the piles were 1, 4, and 5 and A started first, then A was destined to lose as the Nim-Sum at the beginning of the game was 1 XOR 4 XOR 5 = 0 .

Implementation:

In the program below, we play the Nim-Game between computer and human(user) The below program uses two functions knowWinnerBeforePlaying() : : Tells the result before playing. playGame() : plays the full game and finally declare the winner. The function playGame() doesn’t takes input from the human(user), instead it uses a rand() function to randomly pick up a pile and randomly remove any number of stones from the picked pile. The below program can be modified to take input from the user by removing the rand() function and inserting cin or scanf() functions. 

C++




/* A C++ program to implement Game of Nim. The program
assumes that both players are playing optimally */
#include <iostream>
#include <math.h>
using namespace std;
 
#define COMPUTER 1
#define HUMAN 2
 
/* A Structure to hold the two parameters of a move
 
A move has two parameters-
1) pile_index = The index of pile from which stone is
                    going to be removed
2) stones_removed = Number of stones removed from the
                        pile indexed = pile_index */
struct move
{
    int pile_index;
    int stones_removed;
};
 
/*
piles[] -> Array having the initial count of stones/coins
            in each piles before the game has started.
n     -> Number of piles
 
The piles[] are having 0-based indexing*/
 
// A C function to output the current game state.
void showPiles (int piles[], int n)
{
    int i;
    cout <<"Current Game Status -> ";
    for (i=0; i<n; i++)
        cout << " " << piles[i];
    cout <<"\n";
    return;
}
 
// A C function that returns True if game has ended and
// False if game is not yet over
bool gameOver(int piles[], int n)
{
    int i;
    for (i=0; i<n; i++)
        if (piles[i]!=0)
            return (false);
 
    return (true);
}
 
// A C function to declare the winner of the game
void declareWinner(int whoseTurn)
{
    if (whoseTurn == COMPUTER)
        cout <<"\nHUMAN won\n\n";
    else
        cout <<"\nCOMPUTER won\n\n";
    return;
}
 
// A C function to calculate the Nim-Sum at any point
// of the game.
int calculateNimSum(int piles[], int n)
{
    int i, nimsum = piles[0];
    for (i=1; i<n; i++)
        nimsum = nimsum ^ piles[i];
    return(nimsum);
}
 
// A C function to make moves of the Nim Game
void makeMove(int piles[], int n, struct move * moves)
{
    int i, nim_sum = calculateNimSum(piles, n);
 
    // The player having the current turn is on a winning
    // position. So he/she/it play optimally and tries to make
    // Nim-Sum as 0
    if (nim_sum != 0)
    {
        for (i=0; i<n; i++)
        {
            // If this is not an illegal move
            // then make this move.
            if ((piles[i] ^ nim_sum) < piles[i])
            {
                (*moves).pile_index = i;
                (*moves).stones_removed =
                                piles[i]-(piles[i]^nim_sum);
                piles[i] = (piles[i] ^ nim_sum);
                break;
            }
        }
    }
 
    // The player having the current turn is on losing
    // position, so he/she/it can only wait for the opponent
    // to make a mistake(which doesn't happen in this program
    // as both players are playing optimally). He randomly
    // choose a non-empty pile and randomly removes few stones
    // from it. If the opponent doesn't make a mistake,then it
    // doesn't matter which pile this player chooses, as he is
    // destined to lose this game.
 
    // If you want to input yourself then remove the rand()
    // functions and modify the code to take inputs.
    // But remember, you still won't be able to change your
    // fate/prediction.
    else
    {
        // Create an array to hold indices of non-empty piles
        int non_zero_indices[n], count;
 
        for (i=0, count=0; i<n; i++)
            if (piles[i] > 0)
                non_zero_indices [count++] = i;
 
        (*moves).pile_index = (rand() % (count));
        (*moves).stones_removed =
                1 + (rand() % (piles[(*moves).pile_index]));
        piles[(*moves).pile_index] =
        piles[(*moves).pile_index] - (*moves).stones_removed;
 
        if (piles[(*moves).pile_index] < 0)
            piles[(*moves).pile_index]=0;
    }
    return;
}
 
// A C function to play the Game of Nim
void playGame(int piles[], int n, int whoseTurn)
{
    cout <<"\nGAME STARTS\n\n";
    struct move moves;
 
    while (gameOver (piles, n) == false)
    {
        showPiles(piles, n);
 
        makeMove(piles, n, &moves;);
 
        if (whoseTurn == COMPUTER)
        {
            cout <<"COMPUTER removes" << moves.stones_removed << "stones from pile at index "
             << moves.pile_index << endl;
            whoseTurn = HUMAN;
        }
        else
        {
            cout <<"HUMAN removes"<< moves.stones_removed << "stones from pile at index "
            << moves.pile_index << endl;
            whoseTurn = COMPUTER;
        }
    }
 
    showPiles(piles, n);
    declareWinner(whoseTurn);
    return;
}
 
void knowWinnerBeforePlaying(int piles[], int n,
                            int whoseTurn)
{
    cout <<"Prediction before playing the game -> ";
 
    if (calculateNimSum(piles, n) !=0)
    {
        if (whoseTurn == COMPUTER)
            cout <<"COMPUTER will win\n";
        else
            cout <<"HUMAN will win\n";
    }
    else
    {
        if (whoseTurn == COMPUTER)
            cout <<"HUMAN will win\n";
        else
            cout <<"COMPUTER will win\n";
    }
 
    return;
}
 
// Driver program to test above functions
int main()
{
    // Test Case 1
    int piles[] = {3, 4, 5};
    int n = sizeof(piles)/sizeof(piles[0]);
 
    // We will predict the results before playing
    // The COMPUTER starts first
    knowWinnerBeforePlaying(piles, n, COMPUTER);
 
    // Let us play the game with COMPUTER starting first
    // and check whether our prediction was right or not
    playGame(piles, n, COMPUTER);
 
    /*
    Test Case 2
    int piles[] = {3, 4, 7};
    int n = sizeof(piles)/sizeof(piles[0]);
 
    // We will predict the results before playing
    // The HUMAN(You) starts first
    knowWinnerBeforePlaying (piles, n, COMPUTER);
 
    // Let us play the game with COMPUTER starting first
    // and check whether our prediction was right or not
    playGame (piles, n, HUMAN); */
 
    return(0);
}
 
// This code is contributed by shivanisinghss2110


C




/* A C program to implement Game of Nim. The program
   assumes that both players are playing optimally */
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
 
#define COMPUTER 1
#define HUMAN 2
 
/* A Structure to hold the two parameters of a move
 
 A move has two parameters-
  1) pile_index = The index of pile from which stone is
                    going to be removed
  2) stones_removed = Number of stones removed from the
                        pile indexed = pile_index  */
struct move
{
    int pile_index;
    int stones_removed;
};
 
/*
 piles[] -> Array having the initial count of stones/coins
            in each piles before the game has started.
 n       -> Number of piles
 
 The piles[] are having 0-based indexing*/
 
// A C function to output the current game state.
void showPiles (int piles[], int n)
{
    int i;
    printf ("Current Game Status -> ");
    for (i=0; i<n; i++)
        printf ("%d ", piles[i]);
    printf("\n");
    return;
}
 
// A C function that returns True if game has ended and
// False if game is not yet over
bool gameOver(int piles[], int n)
{
    int i;
    for (i=0; i<n; i++)
        if (piles[i]!=0)
            return (false);
 
    return (true);
}
 
// A C function to declare the winner of the game
void declareWinner(int whoseTurn)
{
    if (whoseTurn == COMPUTER)
        printf ("\nHUMAN won\n\n");
    else
        printf("\nCOMPUTER won\n\n");
    return;
}
 
// A C function to calculate the Nim-Sum at any point
// of the game.
int calculateNimSum(int piles[], int n)
{
    int i, nimsum = piles[0];
    for (i=1; i<n; i++)
        nimsum = nimsum ^ piles[i];
    return(nimsum);
}
 
// A C function to make moves of the Nim Game
void makeMove(int piles[], int n, struct move * moves)
{
    int i, nim_sum = calculateNimSum(piles, n);
 
    // The player having the current turn is on a winning
    // position. So he/she/it play optimally and tries to make
    // Nim-Sum as 0
    if (nim_sum != 0)
    {
        for (i=0; i<n; i++)
        {
            // If this is not an illegal move
            // then make this move.
            if ((piles[i] ^ nim_sum) < piles[i])
            {
                (*moves).pile_index = i;
                (*moves).stones_removed =
                                 piles[i]-(piles[i]^nim_sum);
                piles[i] = (piles[i] ^ nim_sum);
                break;
            }
        }
    }
 
    // The player having the current turn is on losing
    // position, so he/she/it can only wait for the opponent
    // to make a mistake(which doesn't happen in this program
    // as both players are playing optimally). He randomly
    // choose a non-empty pile and randomly removes few stones
    // from it. If the opponent doesn't make a mistake,then it
    // doesn't matter which pile this player chooses, as he is
    // destined to lose this game.
 
    // If you want to input yourself then remove the rand()
    // functions and modify the code to take inputs.
    // But remember, you still won't be able to change your
    // fate/prediction.
    else
    {
        // Create an array to hold indices of non-empty piles
        int non_zero_indices[n], count;
 
        for (i=0, count=0; i<n; i++)
            if (piles[i] > 0)
                non_zero_indices [count++] = i;
 
        (*moves).pile_index = (rand() % (count));
        (*moves).stones_removed =
                 1 + (rand() % (piles[(*moves).pile_index]));
        piles[(*moves).pile_index] =
         piles[(*moves).pile_index] - (*moves).stones_removed;
 
        if (piles[(*moves).pile_index] < 0)
            piles[(*moves).pile_index]=0;
    }
    return;
}
 
// A C function to play the Game of Nim
void playGame(int piles[], int n, int whoseTurn)
{
    printf("\nGAME STARTS\n\n");
    struct move moves;
 
    while (gameOver (piles, n) == false)
    {
        showPiles(piles, n);
 
        makeMove(piles, n, &moves;);
 
        if (whoseTurn == COMPUTER)
        {
            printf("COMPUTER removes %d stones from pile "
                   "at index %d\n", moves.stones_removed,
                   moves.pile_index);
            whoseTurn = HUMAN;
        }
        else
        {
            printf("HUMAN removes %d stones from pile at "
                   "index %d\n", moves.stones_removed,
                   moves.pile_index);
            whoseTurn = COMPUTER;
        }
    }
 
    showPiles(piles, n);
    declareWinner(whoseTurn);
    return;
}
 
void knowWinnerBeforePlaying(int piles[], int n,
                             int whoseTurn)
{
    printf("Prediction before playing the game -> ");
 
    if (calculateNimSum(piles, n) !=0)
    {
        if (whoseTurn == COMPUTER)
            printf("COMPUTER will win\n");
        else
            printf("HUMAN will win\n");
    }
    else
    {
        if (whoseTurn == COMPUTER)
            printf("HUMAN will win\n");
        else
            printf("COMPUTER will win\n");
    }
 
    return;
}
 
// Driver program to test above functions
int main()
{
    // Test Case 1
    int piles[] = {3, 4, 5};
    int n = sizeof(piles)/sizeof(piles[0]);
 
    // We will predict the results before playing
    // The COMPUTER starts first
    knowWinnerBeforePlaying(piles, n, COMPUTER);
 
    // Let us play the game with COMPUTER starting first
    // and check whether our prediction was right or not
    playGame(piles, n, COMPUTER);
 
    /*
    Test Case 2
    int piles[] = {3, 4, 7};
    int n = sizeof(piles)/sizeof(piles[0]);
 
    // We will predict the results before playing
    // The HUMAN(You) starts first
    knowWinnerBeforePlaying (piles, n, COMPUTER);
 
    // Let us play the game with COMPUTER starting first
    // and check whether our prediction was right or not
    playGame (piles, n, HUMAN);    */
 
    return(0);
}


Java




/* A Java program to implement Game of Nim. The program
assumes that both players are playing optimally */
 
import java.util.*;
 
 
/* A Class to hold the two parameters of a move
 
A move has two parameters-
1) pile_index = The index of pile from which stone is
                    going to be removed
2) stones_removed = Number of stones removed from the
                        pile indexed = pile_index */
class move {
    public int pile_index;
    public int stones_removed;
};
 
class GFG {
    static int COMPUTER = 1;
    static int HUMAN = 2;
 
    static move moves = new move();
 
    /*
    piles[] -> Array having the initial count of
    stones/coins in each piles before the game has started.
    n     -> Number of piles
 
    The piles[] are having 0-based indexing*/
 
    // A Java function to output the current game state.
    static void showPiles(int[] piles, int n)
    {
        int i;
        System.out.print("Current Game Status -> ");
        for (i = 0; i < n; i++)
            System.out.print(" " + piles[i]);
        System.out.println();
        return;
    }
 
    // A Java function that returns True if game has ended and
    // False if game is not yet over
    static boolean gameOver(int[] piles, int n)
    {
        int i;
        for (i = 0; i < n; i++)
            if (piles[i] != 0)
                return false;
 
        return true;
    }
 
    // A Java function to declare the winner of the game
    static void declareWinner(int whoseTurn)
    {
        if (whoseTurn == COMPUTER)
            System.out.print("\nHUMAN won\n\n");
        else
            System.out.print("\nCOMPUTER won\n\n");
        return;
    }
 
    // A C# function to calculate the Nim-Sum at any point
    // of the game.
    static int calculateNimSum(int[] piles, int n)
    {
        int i, nimsum = piles[0];
        for (i = 1; i < n; i++)
            nimsum = nimsum ^ piles[i];
        return (nimsum);
    }
 
    // A C# function to make moves of the Nim Game
    static void makeMove(int[] piles, int n, move moves)
    {
        // create instance of Random class
        Random rand = new Random();
         
        int i, nim_sum = calculateNimSum(piles, n);
 
        // The player having the current turn is on a
        // winning position. So he/she/it play optimally and
        // tries to make Nim-Sum as 0
        if (nim_sum != 0) {
            for (i = 0; i < n; i++) {
                // If this is not an illegal move
                // then make this move.
                if ((piles[i] ^ nim_sum) < piles[i]) {
                    (moves).pile_index = i;
                    (moves).stones_removed
                        = piles[i] - (piles[i] ^ nim_sum);
                    piles[i] = (piles[i] ^ nim_sum);
                    break;
                }
            }
        }
 
        // The player having the current turn is on losing
        // position, so he/she/it can only wait for the
        // opponent to make a mistake(which doesn't happen
        // in this program as both players are playing
        // optimally). He randomly choose a non-empty pile
        // and randomly removes few stones from it. If the
        // opponent doesn't make a mistake,then it doesn't
        // matter which pile this player chooses, as he is
        // destined to lose this game.
 
        // If you want to input yourself then remove the
        // rand() functions and modify the code to take
        // inputs. But remember, you still won't be able to
        // change your fate/prediction.
        else {
            // Create an array to hold indices of non-empty
            // piles
            int[] non_zero_indices = new int[n];
            int count = 0;
 
            for (i = 0; i < n; i++) {
                if (piles[i] > 0) {
                    non_zero_indices[count] = i;
                    count += 1;
                }
            }
 
            (moves).pile_index = (rand.nextInt(count));
            (moves).stones_removed
                = 1
                  + (rand.nextInt(1 + piles[(moves).pile_index]));
            piles[(moves).pile_index]
                = piles[(moves).pile_index]
                  - (moves).stones_removed;
 
            if (piles[(moves).pile_index] < 0)
                piles[(moves).pile_index] = 0;
        }
        return;
    }
 
    // A C# function to play the Game of Nim
    static void playGame(int[] piles, int n, int whoseTurn)
    {
        System.out.print("\nGAME STARTS\n\n");
 
        while (gameOver(piles, n) == false) {
            showPiles(piles, n);
 
            makeMove(piles, n, moves);
 
            if (whoseTurn == COMPUTER) {
                System.out.println(
                    "COMPUTER removes "
                    + moves.stones_removed
                    + "stones from pile at index "
                    + moves.pile_index);
                whoseTurn = HUMAN;
            }
            else {
                System.out.println(
                    "HUMAN removes" + moves.stones_removed
                    + "stones from pile at index "
                    + moves.pile_index);
                whoseTurn = COMPUTER;
            }
        }
 
        showPiles(piles, n);
        declareWinner(whoseTurn);
        return;
    }
 
    static void knowWinnerBeforePlaying(int[] piles, int n,
                                        int whoseTurn)
    {
        System.out.println(
            "Prediction before playing the game -> ");
 
        if (calculateNimSum(piles, n) != 0) {
            if (whoseTurn == COMPUTER)
                System.out.println("COMPUTER will win\n");
            else
                System.out.println("HUMAN will win\n");
        }
        else {
            if (whoseTurn == COMPUTER)
                System.out.print("HUMAN will win\n");
            else
                System.out.print("COMPUTER will win\n");
        }
 
        return;
    }
 
    // Driver program to test above functions
    public static void main(String[] arg)
    {
        // Test Case 1
        int[] piles = { 3, 4, 5 };
        int n = piles.length;
 
        // We will predict the results before playing
        // The COMPUTER starts first
        knowWinnerBeforePlaying(piles, n, COMPUTER);
 
        // Let us play the game with COMPUTER starting first
        // and check whether our prediction was right or not
        playGame(piles, n, COMPUTER);
 
        /*
        Test Case 2
        int piles[] = {3, 4, 7};
        int n = sizeof(piles)/sizeof(piles[0]);
 
        // We will predict the results before playing
        // The HUMAN(You) starts first
        knowWinnerBeforePlaying (piles, n, COMPUTER);
 
        // Let us play the game with COMPUTER starting first
        // and check whether our prediction was right or not
        playGame (piles, n, HUMAN); */
    }
}
 
// This code is contributed by phasing17


Python3




# A Python3 program to implement Game of Nim. The program
# assumes that both players are playing optimally
import random
 
COMPUTER = 1
HUMAN = 2
 
# A Structure to hold the two parameters of a move
 
# move has two parameters-
# 1) pile_index = The index of pile from which stone is
#                    going to be removed
# 2) stones_removed = Number of stones removed from the
#                        pile indexed = pile_index */
 
 
class move:
 
    def __init__(self):
 
        self.pile_index = 0
        self.stones_removed = 0
 
 
# piles[] -> Array having the initial count of stones/coins
#            in each piles before the game has started.
# n     -> Number of piles
 
# The piles[] are having 0-based indexing
 
# A function to output the current game state.
def showPiles(piles, n):
    print("Current Game Status -> ")
    print(*piles)
 
# A function that returns True if game has ended and
# False if game is not yet over
def gameOver(piles, n):
    for i in range(n):
        if (piles[i] != 0):
            return False
 
    return True
 
# A function to declare the winner of the game
def declareWinner(whoseTurn):
    if (whoseTurn == COMPUTER):
        print("\nHUMAN won")
    else:
        print("\nCOMPUTER won")
    return
 
 
# A function to calculate the Nim-Sum at any point
# of the game.
def calculateNimSum(piles, n):
    nimsum = piles[0]
    for i in range(1, n):
        nimsum = nimsum ^ piles[i]
    return nimsum
 
# A function to make moves of the Nim Game
def makeMove(piles, n, moves):
    nim_sum = calculateNimSum(piles, n)
 
    # The player having the current turn is on a winning
    # position. So he/she/it play optimally and tries to make
    # Nim-Sum as 0
    if (nim_sum != 0):
        for i in range(n):
 
            # If this is not an illegal move
            # then make this move.
            if ((piles[i] ^ nim_sum) < piles[i]):
 
                moves.pile_index = i
                moves.stones_removed = piles[i]-(piles[i] ^ nim_sum)
                piles[i] = (piles[i] ^ nim_sum)
                break
 
    # The player having the current turn is on losing
    # position, so he/she/it can only wait for the opponent
    # to make a mistake(which doesn't happen in this program
    # as both players are playing optimally). He randomly
    # choose a non-empty pile and randomly removes few stones
    # from it. If the opponent doesn't make a mistake,then it
    # doesn't matter which pile this player chooses, as he is
    # destined to lose this game.
 
    # If you want to input yourself then remove the rand()
    # functions and modify the code to take inputs.
    # But remember, you still won't be able to change your
    # fate/prediction.
    else:
        # Create an array to hold indices of non-empty piles
        non_zero_indices = [None for _ in range(n)]
        count = 0
        for i in range(n):
            if (piles[i] > 0):
                non_zero_indices[count] = i
                count += 1
 
        moves.pile_index = int(random.random() * (count))
        moves.stones_removed = 1 + \
            int(random.random() * (piles[moves.pile_index]))
        piles[moves.pile_index] -= moves.stones_removed
 
        if (piles[moves.pile_index] < 0):
            piles[moves.pile_index] = 0
 
    return
 
# A C function to play the Game of Nim
def playGame(piles, n, whoseTurn):
    print("\nGAME STARTS")
    moves = move()
 
    while (gameOver(piles, n) == False):
        showPiles(piles, n)
        makeMove(piles, n, moves)
 
        if (whoseTurn == COMPUTER):
 
            print("COMPUTER removes", moves.stones_removed,
                  "stones from pile at index ", moves.pile_index)
            whoseTurn = HUMAN
 
        else:
            print("HUMAN removes", moves.stones_removed,
                  "stones from pile at index", moves.pile_index)
            whoseTurn = COMPUTER
 
    showPiles(piles, n)
    declareWinner(whoseTurn)
    return
 
def knowWinnerBeforePlaying(piles, n, whoseTurn):
    print("Prediction before playing the game -> ", end="")
    if (calculateNimSum(piles, n) != 0):
 
        if (whoseTurn == COMPUTER):
            print("COMPUTER will win")
        else:
            print("HUMAN will win")
 
    else:
 
        if (whoseTurn == COMPUTER):
            print("HUMAN will win")
        else:
            print("COMPUTER will win")
 
    return
 
# Driver program to test above functions
 
# Test Case 1
piles = [3, 4, 5]
n = len(piles)
 
# We will predict the results before playing
# The COMPUTER starts first
knowWinnerBeforePlaying(piles, n, COMPUTER)
 
# Let us play the game with COMPUTER starting first
# and check whether our prediction was right or not
playGame(piles, n, COMPUTER)
 
# This code is contributed by phasing17


C#




/* A C# program to implement Game of Nim. The program
assumes that both players are playing optimally */
 
using System;
using System.Collections.Generic;
 
/* A Class to hold the two parameters of a move
 
A move has two parameters-
1) pile_index = The index of pile from which stone is
                    going to be removed
2) stones_removed = Number of stones removed from the
                        pile indexed = pile_index */
class move {
    public int pile_index;
    public int stones_removed;
};
 
class GFG {
    static int COMPUTER = 1;
    static int HUMAN = 2;
 
    static move moves = new move();
 
    /*
    piles[] -> Array having the initial count of
    stones/coins in each piles before the game has started.
    n     -> Number of piles
 
    The piles[] are having 0-based indexing*/
 
    // A C# function to output the current game state.
    static void showPiles(int[] piles, int n)
    {
        int i;
        Console.Write("Current Game Status -> ");
        for (i = 0; i < n; i++)
            Console.Write(" " + piles[i]);
        Console.WriteLine();
        return;
    }
 
    // A C# function that returns True if game has ended and
    // False if game is not yet over
    static bool gameOver(int[] piles, int n)
    {
        int i;
        for (i = 0; i < n; i++)
            if (piles[i] != 0)
                return false;
 
        return true;
    }
 
    // A C# function to declare the winner of the game
    static void declareWinner(int whoseTurn)
    {
        if (whoseTurn == COMPUTER)
            Console.Write("\nHUMAN won\n\n");
        else
            Console.Write("\nCOMPUTER won\n\n");
        return;
    }
 
    // A C# function to calculate the Nim-Sum at any point
    // of the game.
    static int calculateNimSum(int[] piles, int n)
    {
        int i, nimsum = piles[0];
        for (i = 1; i < n; i++)
            nimsum = nimsum ^ piles[i];
        return (nimsum);
    }
 
    // A C# function to make moves of the Nim Game
    static void makeMove(int[] piles, int n, move moves)
    {
        var rand = new Random();
        int i, nim_sum = calculateNimSum(piles, n);
 
        // The player having the current turn is on a
        // winning position. So he/she/it play optimally and
        // tries to make Nim-Sum as 0
        if (nim_sum != 0) {
            for (i = 0; i < n; i++) {
                // If this is not an illegal move
                // then make this move.
                if ((piles[i] ^ nim_sum) < piles[i]) {
                    (moves).pile_index = i;
                    (moves).stones_removed
                        = piles[i] - (piles[i] ^ nim_sum);
                    piles[i] = (piles[i] ^ nim_sum);
                    break;
                }
            }
        }
 
        // The player having the current turn is on losing
        // position, so he/she/it can only wait for the
        // opponent to make a mistake(which doesn't happen
        // in this program as both players are playing
        // optimally). He randomly choose a non-empty pile
        // and randomly removes few stones from it. If the
        // opponent doesn't make a mistake,then it doesn't
        // matter which pile this player chooses, as he is
        // destined to lose this game.
 
        // If you want to input yourself then remove the
        // rand() functions and modify the code to take
        // inputs. But remember, you still won't be able to
        // change your fate/prediction.
        else {
            // Create an array to hold indices of non-empty
            // piles
            int[] non_zero_indices = new int[n];
            int count = 0;
 
            for (i = 0; i < n; i++) {
                if (piles[i] > 0) {
                    non_zero_indices[count] = i;
                    count += 1;
                }
            }
 
            (moves).pile_index = (rand.Next(count));
            (moves).stones_removed
                = 1
                  + (rand.Next(piles[(moves).pile_index]));
            piles[(moves).pile_index]
                = piles[(moves).pile_index]
                  - (moves).stones_removed;
 
            if (piles[(moves).pile_index] < 0)
                piles[(moves).pile_index] = 0;
        }
        return;
    }
 
    // A C# function to play the Game of Nim
    static void playGame(int[] piles, int n, int whoseTurn)
    {
        Console.Write("\nGAME STARTS\n\n");
 
        while (gameOver(piles, n) == false) {
            showPiles(piles, n);
 
            makeMove(piles, n, moves);
 
            if (whoseTurn == COMPUTER) {
                Console.WriteLine(
                    "COMPUTER removes "
                    + moves.stones_removed
                    + "stones from pile at index "
                    + moves.pile_index);
                whoseTurn = HUMAN;
            }
            else {
                Console.WriteLine(
                    "HUMAN removes" + moves.stones_removed
                    + "stones from pile at index "
                    + moves.pile_index);
                whoseTurn = COMPUTER;
            }
        }
 
        showPiles(piles, n);
        declareWinner(whoseTurn);
        return;
    }
 
    static void knowWinnerBeforePlaying(int[] piles, int n,
                                        int whoseTurn)
    {
        Console.Write(
            "Prediction before playing the game -> ");
 
        if (calculateNimSum(piles, n) != 0) {
            if (whoseTurn == COMPUTER)
                Console.Write("COMPUTER will win\n");
            else
                Console.Write("HUMAN will win\n");
        }
        else {
            if (whoseTurn == COMPUTER)
                Console.Write("HUMAN will win\n");
            else
                Console.Write("COMPUTER will win\n");
        }
 
        return;
    }
 
    // Driver program to test above functions
    public static void Main(string[] arg)
    {
        // Test Case 1
        int[] piles = { 3, 4, 5 };
        int n = piles.Length;
 
        // We will predict the results before playing
        // The COMPUTER starts first
        knowWinnerBeforePlaying(piles, n, COMPUTER);
 
        // Let us play the game with COMPUTER starting first
        // and check whether our prediction was right or not
        playGame(piles, n, COMPUTER);
 
        /*
        Test Case 2
        int piles[] = {3, 4, 7};
        int n = sizeof(piles)/sizeof(piles[0]);
 
        // We will predict the results before playing
        // The HUMAN(You) starts first
        knowWinnerBeforePlaying (piles, n, COMPUTER);
 
        // Let us play the game with COMPUTER starting first
        // and check whether our prediction was right or not
        playGame (piles, n, HUMAN); */
    }
}
 
// This code is contributed by phasing17


Javascript




/* A JavaScript program to implement Game of Nim. The program
assumes that both players are playing optimally */
 
let COMPUTER = 1;
let HUMAN = 2;
 
/* A Structure to hold the two parameters of a move
 
A move has two parameters-
1) pile_index = The index of pile from which stone is
                    going to be removed
2) stones_removed = Number of stones removed from the
                        pile indexed = pile_index */
class move
{
    constructor()
    {
        this.pile_index;
        this.stones_removed;
         
    }
     
};
 
/*
piles[] -> Array having the initial count of stones/coins
            in each piles before the game has started.
n     -> Number of piles
 
The piles[] are having 0-based indexing*/
 
// A function to output the current game state.
function showPiles (piles, n)
{
    let i;
    process.stdout.write("Current Game Status -> ");
    for (i=0; i<n; i++)
        process.stdout.write(" " + piles[i]);
    process.stdout.write("\n");
    return;
}
 
// A function that returns True if game has ended and
// False if game is not yet over
function gameOver(piles, n)
{
    let i;
    for (i=0; i<n; i++)
        if (piles[i]!=0)
            return false;
 
    return true;
}
 
// A function to declare the winner of the game
function declareWinner(whoseTurn)
{
    if (whoseTurn == COMPUTER)
        console.log("\nHUMAN won\n");
    else
        console.log("\nCOMPUTER won\n");
    return;
}
 
// A function to calculate the Nim-Sum at any point
// of the game.
function calculateNimSum(piles, n)
{
    let i, nimsum = piles[0];
    for (i=1; i<n; i++)
        nimsum = nimsum ^ piles[i];
    return nimsum;
}
 
// A function to make moves of the Nim Game
function makeMove(piles, n, moves)
{
    let i, nim_sum = calculateNimSum(piles, n);
 
    // The player having the current turn is on a winning
    // position. So he/she/it play optimally and tries to make
    // Nim-Sum as 0
    if (nim_sum != 0)
    {
        for (i=0; i<n; i++)
        {
            // If this is not an illegal move
            // then make this move.
            if ((piles[i] ^ nim_sum) < piles[i])
            {
                moves.pile_index = i;
                moves.stones_removed =
                                piles[i]-(piles[i]^nim_sum);
                piles[i] = (piles[i] ^ nim_sum);
                break;
            }
        }
    }
 
    // The player having the current turn is on losing
    // position, so he/she/it can only wait for the opponent
    // to make a mistake(which doesn't happen in this program
    // as both players are playing optimally). He randomly
    // choose a non-empty pile and randomly removes few stones
    // from it. If the opponent doesn't make a mistake,then it
    // doesn't matter which pile this player chooses, as he is
    // destined to lose this game.
 
    // If you want to input yourself then remove the rand()
    // functions and modify the code to take inputs.
    // But remember, you still won't be able to change your
    // fate/prediction.
    else
    {
        // Create an array to hold indices of non-empty piles
        let non_zero_indices = new Array(n);
        let count;
 
        for (i=0, count=0; i<n; i++)
            if (piles[i] > 0)
                non_zero_indices [count++] = i;
 
        moves.pile_index = Math.floor(Math.random() * (count));
        moves.stones_removed = 1 + Math.floor(Math.random() * (piles[moves.pile_index]));
        piles[moves.pile_index] =
        piles[moves.pile_index] - moves.stones_removed;
 
        if (piles[moves.pile_index] < 0)
            piles[moves.pile_index]=0;
    }
    return;
}
 
// A C function to play the Game of Nim
function playGame(piles, n, whoseTurn)
{
    console.log("\nGAME STARTS\n");
    let moves = new move();
 
    while (gameOver (piles, n) == false)
    {
        showPiles(piles, n);
 
        makeMove(piles, n, moves);
 
        if (whoseTurn == COMPUTER)
        {
            console.log("COMPUTER removes", moves.stones_removed, "stones from pile at index ", moves.pile_index);
            whoseTurn = HUMAN;
        }
        else
        {
            console.log("HUMAN removes", moves.stones_removed, "stones from pile at index", moves.pile_index);
            whoseTurn = COMPUTER;
        }
    }
 
    showPiles(piles, n);
    declareWinner(whoseTurn);
    return;
}
 
function knowWinnerBeforePlaying(piles, n, whoseTurn)
{
    process.stdout.write("Prediction before playing the game -> ");
 
    if (calculateNimSum(piles, n) !=0)
    {
        if (whoseTurn == COMPUTER)
            console.log("COMPUTER will win");
        else
            console.log("HUMAN will win");
    }
    else
    {
        if (whoseTurn == COMPUTER)
            console.log("HUMAN will win");
        else
            console.log("COMPUTER will win");
    }
 
    return;
}
 
// Driver program to test above functions
 
// Test Case 1
let piles = [3, 4, 5];
let n = piles.length;
 
// We will predict the results before playing
// The COMPUTER starts first
knowWinnerBeforePlaying(piles, n, COMPUTER);
 
    // Let us play the game with COMPUTER starting first
    // and check whether our prediction was right or not
    playGame(piles, n, COMPUTER);
 
    /*
    Test Case 2
    int piles[] = {3, 4, 7};
    int n = sizeof(piles)/sizeof(piles[0]);
 
    // We will predict the results before playing
    // The HUMAN(You) starts first
    knowWinnerBeforePlaying (piles, n, COMPUTER);
 
    // Let us play the game with COMPUTER starting first
    // and check whether our prediction was right or not
    playGame (piles, n, HUMAN); */
 
 
 
 
// This code is contributed by phasing17


Output : May be different on different runs as random numbers are used to decide next move (for the losing player).

Prediction before playing the game -> COMPUTER will win

GAME STARTS

Current Game Status -> 3 4 5 
COMPUTER removes 2 stones from pile at index 0
Current Game Status -> 1 4 5 
HUMAN removes 3 stones from pile at index 1
Current Game Status -> 1 1 5 
COMPUTER removes 5 stones from pile at index 2
Current Game Status -> 1 1 0 
HUMAN removes 1 stones from pile at index 1
Current Game Status -> 1 0 0 
COMPUTER removes 1 stones from pile at index 0
Current Game Status -> 0 0 0 

COMPUTER won

References : https://en.wikipedia.org/wiki/Nim



Previous Article
Next Article

Similar Reads

Combinatorial Game Theory | Set 1 (Introduction)
Combinatorial games are two-person games with perfect information and no chance moves (no randomization like coin toss is involved that can effect the game). These games have a win-or-lose or tie outcome and determined by a set of positions, including an initial position, and the player whose turn it is to move. Play moves from one position to anot
3 min read
Combinatorial Game Theory | Set 3 (Grundy Numbers/Numbers and Mex)
We have introduced Combinatorial Game Theory in Set 1 and discussed Game of Nim in Set 2.Grundy Number is a number that defines a state of a game. We can define any impartial game (example : nim game) in terms of Grundy Number. Grundy Numbers or Numbers determine how any Impartial Game (not only the Game of Nim) can be solved once we have calculate
15+ min read
Combinatorial Game Theory | Set 4 (Sprague - Grundy Theorem)
Prerequisites : Grundy Numbers/Numbers and MexWe have already seen in Set 2 (https://www.cdn.geeksforgeeks.org/combinatorial-game-theory-set-2-game-nim/), that we can find who wins in a game of Nim without actually playing the game.Suppose we change the classic Nim game a bit. This time each player can only remove 1, 2 or 3 stones only (and not any
15 min read
Game Theory (Normal form game) | Set 2 (Game with Pure Strategy)
Game Theory (Normal – form game) | Set 1 (Introduction) Please go through the above article before proceeding. Given a payoff matrix. The task is to find the optimum strategies of the players. Solution: Player A is having 3 strategies - 1, 2 and 3, and player B is also having 3 strategies - 1, 2 and 3. Step 1: Find row minimum values for each row a
2 min read
Game Theory (Normal-form game) | Set 3 (Game with Mixed Strategy)
Consider the following payoff matrix with respect to player A and solve it optimally. Solution: If a game has no saddle point then the game is said to have mixed strategy. Step 1: Find out the row minimum and column maximum. Step 2: Find out the minimax and maximin values. Since minimax and maximin value of this game are not equal, this game has no
4 min read
Game Theory (Normal-form Game) | Set 7 (Graphical Method [M X 2] Game)
The payoff matrix of an M * 2 game consists of M rows and two columns. This article will discuss how to solve an M * 2 game by graphical method. Also, this article will discuss if more than two lines intersect the same point in the graph then how can a 2 * 2 payoff matrix be formed. Consider the below problem: Solution: First check whether the prob
3 min read
Game Theory (Normal-form Game) | Set 6 (Graphical Method [2 X N] Game)
The payoff matrix of a 2 * N game consists of 2 rows and N columns . This article will discuss how to solve a 2 * N game by graphical method. Consider the below 2 * 5 game: Solution: First check the saddle point of the game. This game has no saddle point. Step 1: Reduce the size of the payoff matrix by applying dominance property, if it exists. Thi
3 min read
A modified game of Nim
Given an array arr[] of integers, two players A and B are playing a game where A can remove any number of non-zero elements from the array that are multiples of 3. Similarly, B can remove multiples of 5. The player who can't remove any element loses the game. The task is to find the winner of the game if A starts first and both play optimally.Examp
7 min read
Variation in Nim Game
Prerequisites: Sprague Grundy theorem Grundy NumbersNim is a famous game in which two players take turns removing items from distinct piles. During each turn, a player must remove one or more items from a single, non-empty pile. The winner of the game is whichever player removes the last item from the last non-empty pile. Now, For each non-empty pi
8 min read
Number of ways for playing first move optimally in a NIM game
Two players A and B are playing NIM Game with each other. Both are playing optimally. Player A starts the game. The task is to find the number of ways of playing 1st move for A to ensure a winning strategy for A if possible, otherwise, print -1. Examples: Input: arr[] = {1, 2, 3} Output: -1 There is no winning strategy for A no matter how optimally
8 min read
Find the winner in nim-game
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 i
7 min read
Game of Nim with removal of one stone allowed
In Game of Nim, two players take turns removing objects from heaps or the pile of stones. Suppose two players A and B are playing the game. Each is allowed to take only one stone from the pile. The player who picks the last stone of the pile will win the game. Given N the number of stones in the pile, the task is to find the winner, if player A sta
4 min read
Game Theory (Normal - form game) | Set 1 (Introduction)
Game theory is a mathematical model used for decision making. It has applications in all fields of social science, as well as in logic and computer science. Game theory has come to play an increasingly important role in logic and in computer science. To be fully defined, a game must specify the following elements: the players of the game, the infor
4 min read
Game Theory (Normal-form Game) | Set 5 (Dominance Property-Mixed Strategy)
This article discusses how to solve a game by the dominance property with mixed strategy. Consider the below game: Solution: Find out the row minimum and column maximum values. Here Minimax value is not equal to Maximin so this game has no saddle point. Now proceed with dominance property to reduce the rows and the columns. Reducing the row and the
2 min read
Game Theory (Normal-form Game) | Set 4 (Dominance Property-Pure Strategy)
In some of the games, it is possible to reduce the size of the payoff matrix by eliminating rows (or columns) that are dominated by other rows (or columns) respectively. Dominance property for rows: X ≤ Y i.e. if all the elements of a particular row X are less than or equal to the corresponding elements of another row Y then delete row X (row X is
4 min read
Minimax Algorithm in Game Theory | Set 1 (Introduction)
Minimax is a kind of backtracking algorithm that is used in decision making and game theory to find the optimal move for a player, assuming that your opponent also plays optimally. It is widely used in two player turn-based games such as Tic-Tac-Toe, Backgammon, Mancala, Chess, etc.In Minimax the two players are called maximizer and minimizer. The
9 min read
Minimax Algorithm in Game Theory | Set 4 (Alpha-Beta Pruning)
Prerequisites: Minimax Algorithm in Game Theory, Evaluation Function in Game TheoryAlpha-Beta pruning is not actually a new algorithm, but rather an optimization technique for the minimax algorithm. It reduces the computation time by a huge factor. This allows us to search much faster and even go into deeper levels in the game tree. It cuts off bra
11 min read
Minimax Algorithm in Game Theory | Set 5 (Zobrist Hashing)
Previous posts on this topic : Minimax Algorithm in Game Theory, Evaluation Function in Game Theory, Tic-Tac-Toe AI – Finding optimal move, Alpha-Beta Pruning.Zobrist Hashing is a hashing function that is widely used in 2 player board games. It is the most common hashing function used in transposition table. Transposition tables basically store the
12 min read
Expectimax Algorithm in Game Theory
The Expectimax search algorithm is a game theory algorithm used to maximize the expected utility. It is a variation of the Minimax algorithm. While Minimax assumes that the adversary(the minimizer) plays optimally, the Expectimax doesn't. This is useful for modelling environments where adversary agents are not optimal, or their actions are based on
8 min read
Pareto Optimality and its application in Game Theory
Prerequisites: Game Theory When the strategies from game theory are discussed, they are often mentioned from a player's perspective. However, when the strategies are formed from an observer's angle whose main motive is to wish for the best outcome for every player; that is, when strategies are formed from a socially balanced viewpoint, then the out
5 min read
Practice Problems on Game Theory
Game Theory is a topic in competitive programming that involves a certain type of problem, where there are some players who play a game based on given rules and the task is often to find the winner or the winning moves. Game Theory is often asked in short contests with a mixture of other topics like range querying or greedy or dynamic programming.
4 min read
Introduction to Evaluation Function of Minimax Algorithm in Game Theory
Prerequisite: Minimax Algorithm in Game TheoryAs seen in the above article, each leaf node had a value associated with it. We had stored this value in an array. But in the real world when we are creating a program to play Tic-Tac-Toe, Chess, Backgammon, etc. we need to implement a function that calculates the value of the board depending on the pla
8 min read
Finding optimal move in Tic-Tac-Toe using Minimax Algorithm in Game Theory
Prerequisites: Minimax Algorithm in Game Theory, Evaluation Function in Game TheoryLet us combine what we have learnt so far about minimax and evaluation function to write a proper Tic-Tac-Toe AI (Artificial Intelligence) that plays a perfect game. This AI will consider all possible scenarios and makes the most optimal move. Finding the Best Move :
15+ min read
The prisoner's dilemma in Game theory
Two members of a criminal gang are arrested and imprisoned. Each prisoner is in solitary confinement with no means of communicating with the other. The prosecutors lack sufficient evidence to convict the pair on the principal charge. They hope to get both sentenced to a year in prison on a lesser charge. Simultaneously, the prosecutors offer each p
3 min read
Dynamic Programming in Game Theory for Competitive Programming
In the fast-paced world of competitive programming, mastering dynamic programming in game theory is the key to solving complex strategic challenges. This article explores how dynamic programming in game theory can enhance your problem-solving skills and strategic insights, giving you a competitive edge. Whether you're a seasoned coder or a newcomer
15+ min read
Game Theory
Game Theory is a topic in competitive programming that involves a certain type of problem, where there are some players who play a game based on given rules and the task is often to find the winner or the winning moves. Game Theory is often asked in short contests with a mixture of other topics like range querying or greedy or dynamic programming.
15+ min read
Proof that Independent Set in Graph theory is NP Complete
Prerequisite: NP-Completeness, Independent set. An Independent Set S of graph G = (V, E) is a set of vertices such that no two vertices in S are adjacent to each other. It consists of non- adjacent vertices. Problem: Given a graph G(V, E) and an integer k, the problem is to determine if the graph contains an independent set of vertices of size &gt;
5 min read
Mathematics | Graph Theory Basics - Set 1
A graph is a data structure that is defined by two components : A node or a vertex.An edge E or ordered pair is a connection between two nodes u,v that is identified by unique pair(u,v). The pair (u,v) is ordered because (u,v) is not same as (v,u) in case of directed graph.The edge may have a weight or is set to one in case of unweighted graph.Cons
4 min read
Winning Game by replacing numbers with factors (Brain Game)
Given 2 players A and B take turns alternatively to play a game in which they have N numbers on a paper. In one turn, a player can replace one of the numbers by any of its factors (except for 1 &amp; the number itself). The player who is unable to make a move loses the game. Find the winner of the game if A starts the game and both play optimally.
15+ min read
Game of Chocolates | Wythoff's Game
Bunty and Dolly are playing a game, described as follows:There are two boxes having A and B number of chocolates respectively. Both can eat L (L &gt;= 1) chocolates from any one box or L chocolates from both boxes in one move. They play the game alternatively and the last one to eat the chocolate will be the winner. You have to help Bunty in decidi
13 min read
Article Tags :
Practice Tags :