From 4ff2a9dd4e1a517cb0526ff51233bb6f1fc3fc8d Mon Sep 17 00:00:00 2001 From: Aditi Agarwal <31546143+aditiagarwal34550@users.noreply.github.com> Date: Sat, 6 Jul 2019 21:59:58 -0700 Subject: [PATCH] minimax (#947) * minimax.py minimax algorithm is used for game like tic tac toe. It traces the path and selects the optimal move. * minimax.py Minimax is used in decision making and game theory to find the optimal move for a player, when your opponent also plays optimally. It is widely used in games like Tic-Tac-Toe, Chess. * Delete minimax.py * Update minimax.py * Minimax is a backtracking algorithm that is used in game theory to find the optimal move for a player, assuming that your opponent also plays optimally --- backtracking/minimax.py | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 backtracking/minimax.py diff --git a/backtracking/minimax.py b/backtracking/minimax.py new file mode 100644 index 000000000..5168306e7 --- /dev/null +++ b/backtracking/minimax.py @@ -0,0 +1,28 @@ +import math + +''' Minimax helps to achieve maximum score in a game by checking all possible moves + depth is current depth in game tree. + nodeIndex is index of current node in scores[]. + if move is of maximizer return true else false + leaves of game tree is stored in scores[] + height is maximum height of Game tree +''' + +def minimax (Depth, nodeIndex, isMax, scores, height): + + if Depth == height: + return scores[nodeIndex] + + if isMax: + return (max(minimax(Depth + 1, nodeIndex * 2, False, scores, height), + minimax(Depth + 1, nodeIndex * 2 + 1, False, scores, height))) + return (min(minimax(Depth + 1, nodeIndex * 2, True, scores, height), + minimax(Depth + 1, nodeIndex * 2 + 1, True, scores, height))) + +if __name__ == "__main__": + + scores = [90, 23, 6, 33, 21, 65, 123, 34423] + height = math.log(len(scores), 2) + + print("Optimal value : ", end = "") + print(minimax(0, 0, True, scores, height))