Created
July 4, 2020 21:24
-
-
Save alldroll/9031a1f34918ff858cb78db281dcba5c to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const ( | |
playerNone = 0 | |
playerA = 1 | |
playerB = 2 | |
) | |
type line struct { | |
count int | |
player int | |
} | |
func (l line) isOneOf(players ...int) (success bool) { | |
for _, p := range players { | |
if success = (p == l.player); success { | |
break | |
} | |
} | |
return success | |
} | |
type TicTacToe struct { | |
rows []line | |
cols []line | |
diags []line | |
} | |
/** Initialize your data structure here. */ | |
func Constructor(n int) TicTacToe { | |
return TicTacToe{ | |
rows: make([]line, n), | |
cols: make([]line, n), | |
diags: make([]line, 2), | |
} | |
} | |
/** 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: Player 2 wins. */ | |
func (t *TicTacToe) Move(row int, col int, player int) int { | |
n := len(t.rows) | |
if t.rows[row].isOneOf(player, playerNone) { | |
t.rows[row].player = player | |
t.rows[row].count++ | |
} | |
if t.cols[col].isOneOf(player, playerNone) { | |
t.cols[col].player = player | |
t.cols[col].count++ | |
} | |
// (0, 0), (1, 1), (2, 2) | |
// (n - 1, 0), (n - 2, 1) | |
if col == row && t.diags[0].isOneOf(player, playerNone) { | |
t.diags[0].player = player | |
t.diags[0].count++ | |
} | |
if col == (n - row - 1) && t.diags[1].isOneOf(player, playerNone) { | |
t.diags[1].player = player | |
t.diags[1].count++ | |
} | |
if t.diags[0].player == player && t.diags[0].count == n { | |
return player | |
} | |
if t.diags[1].player == player && t.diags[1].count == n { | |
return player | |
} | |
if t.rows[row].player == player && t.rows[row].count == n { | |
return player | |
} | |
if t.cols[col].player == player && t.cols[col].count == n { | |
return player | |
} | |
return playerNone | |
} | |
/** | |
* Your TicTacToe object will be instantiated and called as such: | |
* obj := Constructor(n); | |
* param_1 := obj.Move(row,col,player); | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment