MCPcopy
hub / github.com/austingebauer/go-leetcode / Move

Method Move

design_tic_tac_toe_348/solution.go:28–70  ·  view source on GitHub ↗

** Player {player} makes a move at ({row}, {col}). @param row The row of the board. @param col The column of the board. @param player The player, can be either 1 or 2. @return The current winning condition, can be either: 0: No one wins. 1: Player 1 wins. 2: Pla

(row int, col int, player int)

Source from the content-addressed store, hash-verified

26 1: Player 1 wins.
27 2: Player 2 wins. */
28func (this *TicTacToe) Move(row int, col int, player int) int {
29 // Note: intuition is that each row, col, and diagonal has a count.
30 // For a player to win, it's count must be equal to the row, col, or diagonal length.
31 // Let's choose +1 for player 1 and -1 from player 2. If the absolute value of the
32 // count for row, col, diagonals ever reaches the size of the grid, then the player
33 // has won. This behavior assumes each move is valid and into an empty block.
34
35 // the count for x (player 1) is 1
36 // the count for o (player 2) is -1
37 count := 1
38 if player == 2 {
39 count = -1
40 }
41
42 // increase the counts for each row and column
43 this.rowCounts[row] += count
44 this.colCounts[col] += count
45
46 // increase backward slash diagonal count
47 if row == col {
48 this.backwardDiagCount += count
49 }
50
51 // increase forward slash diagonal count
52 // tricky observation for the forward slash diagonal
53 // works for matching on columns as well
54 if row == len(this.rowCounts)-col-1 {
55 this.forwardDiagCount += count
56 }
57
58 // if the count at this move becomes 3 or -3, the current player
59 // just won the game.
60 boardSize := len(this.rowCounts)
61 if int(math.Abs(float64(this.rowCounts[row]))) == boardSize ||
62 int(math.Abs(float64(this.colCounts[col]))) == boardSize ||
63 int(math.Abs(float64(this.forwardDiagCount))) == boardSize ||
64 int(math.Abs(float64(this.backwardDiagCount))) == boardSize {
65 return player
66 }
67
68 // no-one won the game
69 return 0
70}

Callers 7

TestTicTacToeXWinsRowFunction · 0.80
TestTicTacToeXWinsColFunction · 0.80
TestTicTacToeOWinsRowFunction · 0.80
TestTicTacToeOWinsColFunction · 0.80
TestTicTacToeNoWinsFunction · 0.80

Calls

no outgoing calls

Tested by 7

TestTicTacToeXWinsRowFunction · 0.64
TestTicTacToeXWinsColFunction · 0.64
TestTicTacToeOWinsRowFunction · 0.64
TestTicTacToeOWinsColFunction · 0.64
TestTicTacToeNoWinsFunction · 0.64