Game Theory

Consider the simpler problem:

You are playing the following Nim Game with your friend:

  • Initially, there is a heap of stones on the table.
  • You and your friend will alternate taking turns, and you go first.
  • On each turn, the person whose turn it is will remove 1 to 3 stones from the heap.
  • The one who removes the last stone is the winner.

Given n, the number of stones in the heap, return true if you can win the game assuming both you and your friend play optimally, otherwise return false.

The answer to this problem is simply

if(canWin(n-1)|| canWin(n-2)|| canWin(n-3)
return false
return true

Basically we have to ensure that no matter what the opponent does — he never had a chance to win.

** Force A Win

Consider another problem when the first player to play can “force a win”. In other words, we would like to stop the recursion tree as soon as we see a result of winning from a player

Cat and Mouse



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store