minimax.go
package tictactoe
// Minimax is for retrieving the optimal value for maximizer.
// depth is the current depth in the game tree
// nodeIndex is the current index of node in scores
// isMax is true if the current move is a maximizer
// scores stores the Game Tree
// height is the max height of the Game Tree
func Minimax(depth, nodeIndex int, isMax bool, scores []int, height int) int {
// terminate if end of the tree reached
if depth == height {
return scores[nodeIndex]
}
if isMax {
left := Minimax(depth+1, nodeIndex*2, false, scores, height)
right := Minimax(depth+1, nodeIndex*2+1, false, scores, height)
return max(left, right)
}
left := Minimax(depth+1, nodeIndex*2, true, scores, height)
right := Minimax(depth+1, nodeIndex*2+1, true, scores, height)
return min(left, right)
}
func max(a, b int) int {
if a > b {
return a
}
return b
}
func min(a, b int) int {
if a < b {
return a
}
return b
}