[Golang] Leetcode - 292. Nim game (mathematics)

[Golang] Leetcode - 292. Nim game (mathematics)

Topic : You and your friend, two people play Nim game together:

There is a pile of stones on the table. You take turns taking your turns, with you going first . Each turn, the person whose turn it is takes away 1 - 3 stones. The person who removes the last stone is the winner.

Assume that every step of yours is the optimal solution. Please write a function to determine whether you can win the game given the number of stones n. If you can win, return true; otherwise, return false.

Link : Leetcode - 292. Nim game .

Example 1:

Input: n = 4
Output: false
Explanation: The following are possible outcomes:

  1. Remove 1 stone. Your friend removes 3 stones, including the last one. Your friend has won.
  2. Remove 2 stones. Your friend removes 2 stones, including the last one. Your friend has won.
  3. You remove 3 stones. Your friend removed the last stone. Your friend has won.
    In all outcomes, your friend is the winner.

Example 2:

Input: n = 1
Output: true

Example 3:

Input: n = 2
Output: true

Idea: If there are only 1, 2, or 3 stones in the pile, then in your turn, you can take all the stones and win the game; if there are exactly 4 stones in the pile, you will lose. Because in this case, no matter how many stones you take away, there will always be a few left for your opponent, who can take all the remaining stones, so that he can beat you in the game. Therefore, in order to win, you must avoid situations where the number of stones in the pile is 4 during your turn.

Continue to reason, assuming that there are only 5, 6, or 7 stones left in the current pile, you can control the number of stones you take, and always leave exactly 4 stones for your opponent, making him lose the game. But if there are 8 stones in the pile, you will inevitably lose, because no matter you pick 1, 2, 3 stones from the pile, your opponent can choose 3, 2, 1, and then Make sure that when it's your turn again, you face 4 stones. Obviously, if we continue to reason, we can see that it will repeat n = 4, 8, 12, 16, ... in the same pattern, basically it can be seen that if the number of stones in the pile is a multiple of 4, you will definitely lose the game .

number of stones win or lose
1-3 true
4 false
5-7 true (Leave 4 to the opponent and he will lose no matter what)
8 false (the opponent can give you 4 and let you lose)
9-11 true (give the opponent 8 and he will lose no matter what)
12 false (the opponent can give you 8 left and let you lose)

Go code:

package main

import "fmt"

func canWinNim(n int) bool {
    
    
	if n%4 == 0 {
    
    
		return false
	}
	return true
}

func main() {
    
    
	fmt.Println(canWinNim(4))
}

Submit a screenshot:
insert image description here

Guess you like

Origin blog.csdn.net/a6661314/article/details/124941358