Download presentation
Presentation is loading. Please wait.
1
Team Dont Block Me, National Taiwan University
d038: Nim Game (Again) Po-Lung Chen Team Dont Block Me, National Taiwan University March 26, 2010
2
Nim Game The Nim Game consists of some piles of stones, and the players take turn to grab stones from some pile(s). The player who grabs the last stone loses the game. pile1 pile2 pile3
3
Problem Description (1/3)
A Nim Game variant: 2 piles of stones, each pile consists of zero or more stones. 2 players, alternately grab stones from the pile(s). The one who grabs the last stone loses the game. Grabbing rule: Grab at least one stone from one of the two piles. Grab from each of the two piles the same number of stones.
4
Problem Description (2/3)
The player who does NOT grab first will have one chance of launching a “counterattack” during the game play. Counterattack:
5
Problem Description (3/3)
Two experts playing this new Nim game. Their strategies are always the best possible. If the current situation would lead to a win: choose the way minimizing #steps. If the current situation would lead to a loss: choose the way maximizing #steps. Given the number of the stones and , Determine: (1) First player will win or lose. (2) The total number of steps in this game.
6
Solution (1/4) This problem can be solved by dynamic programming.
A “state” of the game consists of: # of stones in first pile # of stones in second pile the current player has the chance to use counterattack? the other player has the chance to use counterattack? A win/lose function can be determined by the “state”. can be “WIN” or “LOSS”
7
Solution (2/4) The recurrence relation: The initial condition:
“WIN”, if Otherwise “LOSS” The initial condition: , , and are all “WIN” states.
8
Solution (3/4) Similarly, we can define the function for the number of steps in game according to players’ strategies. Case 1 (the state is going to win): Find minimum (if possible)
9
Solution (4/4) Case 2 (the state is going to lose):
For initial conditions, set them all to zero. Find maximum (if possible)
10
Time Complexity Let be the maximum number of stones +1 in a pile.
The number of possible states is no more than Calculation time for a state is Therefore the time complexity is We can use pre-calculation to find out the answer to all the possible states.
11
Implementation Details
Be careful! The maximum number of stones in a pile can be 110, not 100. This might cause runtime error if the array is too small.
12
Finally… Thanks for your attention!
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.