From ed39288bf9d584f563f5896ae87eb4ac909e0b61 Mon Sep 17 00:00:00 2001 From: Soumya Pandey <43310171+100mya@users.noreply.github.com> Date: Fri, 13 Oct 2023 15:59:54 +0530 Subject: [PATCH] Create minmax.js --- Backtracking/minmax.js | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 Backtracking/minmax.js diff --git a/Backtracking/minmax.js b/Backtracking/minmax.js new file mode 100644 index 0000000000..da7e940b70 --- /dev/null +++ b/Backtracking/minmax.js @@ -0,0 +1,32 @@ +function minimax(depth, nodeIndex, isMax, scores, height) { + if (depth < 0) { + throw new Error("Depth cannot be less than 0"); + } + + if (scores.length === 0) { + throw new Error("Scores cannot be empty"); + } + + if (depth === height) { + return scores[nodeIndex]; + } + + if (isMax) { + const leftChildIndex = nodeIndex * 2; + const rightChildIndex = nodeIndex * 2 + 1; + const leftValue = minimax(depth + 1, leftChildIndex, false, scores, height); + const rightValue = minimax(depth + 1, rightChildIndex, false, scores, height); + return Math.max(leftValue, rightValue); + } else { + const leftChildIndex = nodeIndex * 2; + const rightChildIndex = nodeIndex * 2 + 1; + const leftValue = minimax(depth + 1, leftChildIndex, true, scores, height); + const rightValue = minimax(depth + 1, rightChildIndex, true, scores, height); + return Math.min(leftValue, rightValue); + } +} + +const scores = [90, 23, 6, 33, 21, 65, 123, 34423]; +const height = Math.log2(scores.length); + +console.log("Optimal value: " + minimax(0, 0, true, scores, height));