Nim Game

Question

You are playing the following Nim Game with your friend: There is a heap of stones on the table, each time one of you take turns to remove 1 to 3 stones. The one who removes the last stone will be the winner. You will take the first turn to remove the stones.

Both of you are very clever and have optimal strategies for the game. Write a function to determine whether you can win the game given the number of stones in the heap.

For example, if there are 4 stones in the heap, then you will never win the game: no matter 1, 2, or 3 stones you remove, the last stone will always be removed by your friend.

Tags

  • Dynamic Programming
  • Mathematics

Thought

Two solutions:

  • Dynamic Programming
  • Mathematics

For the first algorithm. We need to build a DP array with size of 4 for recursion function. However, in this problem, the DP algorithm will not pass the Time Limit requirement.

Thus, we need to use another algorithm which is simpler. According to the reference, when number n can be divided by 4, the opponent will win.

Code

DP algorithm

class Solution(object):
    def canWinNim(self, n):
        """
        DP problem
        :type n: int
        :rtype: bool
        """
        if n <= 3:
            return True
        DP = [None for _ in xrange(4)]
        DP[:3] = [True, True, True]
        for i in xrange(3, n):
            DP[3] = (not DP[2]) or (not DP[1]) or (not DP[0])
            DP[:3] = DP[1:]
        return DP[3]

Mathematics

class Solution(object):
    def canWinNim(self, n):
        """
        :type n: int
        :rtype: bool
        """
        return n % 4 > 0

results matching ""

    No results matching ""