You’re trying to decide who will win a game assuming optimal choices. The idea is there are x number of spaces, _ _ _ _ _ _ _. Player one goes and marks two consecutive spots. Then player two goes and does the same. The first player who cannot go WINS. So given the board before, this is one possiblity:
P1: x x _ _ _ _ _
P2: x x _ x x _ _
P1: x x _ x x x x
So player 2 wins. You’re given an array where 0 represents a free space and 1 represents a marked spot. The array may have some spots already marked.
The only way I can think to do this is check every move, and for every move check if every possible move after results in a win. I can’t even fully figure out how I would do this, but I was hoping there was a better way. Any ideas?
You should work problems like this backwards.
Given all the possible game states, go through and decide which is a win for player 1 (W) and which is a win for player 2 (L). Initially, you only know the answer for the states where no one can play. In this case the answer is
Wif no two consecutive spots and total number of taken spots is4kLif no two consecutive spots and total number of taken spots is4k+2Now work backwards. If there is any board position from which player 1 can move to a
W, mark that asW, and if there is any board position from which player 2 can move to aL, mark that asL. Again, this won’t get all positions marked right away, but iterating this will. The iterative part is thisWif there are4k+2spots and two consecutive spots which, when filled, give position markedWLif there are4kspots and two consecutive spots which, when filled, give position markedLExample: Consider the board
_ _ _ _ _ _. Evaluate from the final states working backwardsPlayer Two to move:
Player One to move:
Player Two to move:
Player One to move:
You can program this recursively so that each position will be evaluated as
WorL. Let each board positionPbe represented by a binary vector of lengthnwhere1denotes a taken spot and0denotes an open spot. Here’s the pseudocode fordoesPlayerOneWin: