Infinite recursion - Javascript minimax - javascript

I am trying to create a chess AI using the chess.js library. I am using the minimax solution with Alpha-Beta pruning, but for some reason, when the program runs it continues even after the depth reaches 0. Can anyone tell me why?
var Buddha = function() {
this.movehistory = 0;
this.color = "b";
this.opp = "w";
this.minimax = function(board, depth, alpha, beta) {
console.log(depth);
if(depth === 0 || board.game_over() === true) {
console.log("Depth == 0");
return [this.eval_board(board), null]
} else {
if(board.turn() === this.color) {
var bestmove = null
var possible_moves = board.moves()
for (index = 0; index < possible_moves.length; ++index) {
var new_board = new Chess(board.fen());
new_board.move(possible_moves[index])
var mini = this.minimax(new_board, --depth, alpha, beta)
var score = mini[0];
var move = mini[1];
if(score > alpha) {
alpha = score;
bestmove = possible_moves[index];
if(alpha >= beta) {
break;
}
}
}
return [alpha, bestmove]
} else if(board.turn() === this.opp) {
var bestmove = null
var possible_moves = board.moves()
for (index = 0; index < possible_moves.length; ++index) {
var new_board = new Chess(board.fen());
new_board.move(possible_moves[index])
var mini = this.minimax(new_board, --depth, alpha, beta)
var score = mini[0];
var move = mini[1];
if(score < beta) {
beta = score;
bestmove = possible_moves[index];
if(alpha >= beta) {
break;
}
}
}
return [beta, bestmove]
}
}
}
this.eval_board = function(board) {
if(board.in_check()) {
if(board.turn() == this.opp) {
return Number.POSITIVE_INFINITY;
} else {
return Number.NEGATIVE_INFINITY;
}
} else if(board.in_checkmate()) {
if(board.turn() == this.opp) {
return Number.POSITIVE_INFINITY;
} else {
return Number.NEGATIVE_INFINITY;
}
} else if(board.in_stalemate()) {
if(board.turn() == this.opp) {
return Number.POSITIVE_INFINITY;
} else {
return Number.NEGATIVE_INFINITY;
}
}
}
this.move = function(board) {
var bestmove = this.minimax(board, 1, Number.NEGATIVE_INFINITY, Number.POSITIVE_INFINITY)
}
}

function minimax(board, depth, alpha, beta) {
if(depth === 0 …) { …
return …
} else {
…
for (index = 0; index < possible_moves.length; ++index) {
… minimax(new_board, --depth, alpha, beta)
// ^^
…
}
}
}
Here you're decrementing the depth in a loop. Use depth <= 0 for the base case, and/or pass depth - 1 as an argument or put the decrement statement before the loop.

Related

find the overlap between two strings

I have a string and need to check with and get whether the following strings overlap with the start and end of my target string:
target string: "click on the Run"
search strings: "the Run button to", "code and click on"
Apparently:
"the Run button to" is overlapped at the end of target "click on the Run"
"code and click on" is overlapped at the start of target "click on the Run"
Both, "the Run" and "click on" will be the desired results.
I have come up with a function to check and get the overlapped results for the cases at the start and at the end separately.
Question:
But my code could not be able to get the expected results only if I know how the search string overlapped with the target string in the very first place. And how can I combine the searched results in one go as well?
function findOverlapAtEnd(a, b) {
if (b.length === 2) {
return "";
}
if (a.indexOf(b) >= 0) {
return b;
}
if (a.endsWith(b)) {
return b;
}
return findOverlapAtEnd(a, b.substring(0, b.length - 1));
}
function findOverlapAtStart(a, b) {
if (b.length === 2) {
return "";
}
if (a.indexOf(b) >= 0) {
return b;
}
if (a.startsWith(b)) {
return b;
}
return findOverlapAtStart(a, b.substring(1));
}
console.log(findOverlapAtEnd("click on the Run", "the Run button to"))
console.log(findOverlapAtStart("click on the Run", "code and click on"))
edited:
case in the middle is also considered, e.g.:
target string: "click on the Run"
search strings: "on the"
Return value: "on the"
You may try this
function findOverlapAtEnd(a, b, min) {
if (b.length <= min) {
return '';
}
if (a.indexOf(b) >= 0) {
return b;
}
if (a.endsWith(b)) {
return b;
}
return findOverlapAtEnd(a, b.substring(0, b.length - 1), min);
}
function findOverlapAtStart(a, b, min) {
if (b.length <= min) {
return '';
}
if (a.indexOf(b) >= 0) {
return b;
}
if (a.startsWith(b)) {
return b;
}
return findOverlapAtStart(a, b.substring(1), min);
}
const GetOverlappingSection = (target, search, min) => {
if (target.length < search.length) {
const tmp = target;
target = search;
search = tmp;
}
let overlap1 = findOverlapAtStart(target, search, min);
if (overlap1.length === 0) {
overlap1 = findOverlapAtEnd(target, search, min);
}
return overlap1;
};
const removeEmptyKeyword = overlap => {
let tmpFinaloverlap = [];
overlap.forEach((key, idx) => {
if (!(key.trim().length === 0)) {
tmpFinaloverlap = [...tmpFinaloverlap, key];
}
});
return tmpFinaloverlap;
};
// let overlap = ['click on','the Run']
const GetOverlappingOfKeyowrd1And2 = (keywordSet1, keywordSet2,min) => {
let resultSetoverlap = [];
let tmpresultSetoverlap = [];
keywordSet1.forEach(key =>
keywordSet2.forEach(k2 => {
tmpresultSetoverlap = [
...tmpresultSetoverlap,
GetOverlappingSection(key, k2, min),
];
})
);
// get the resultSetoverlap
tmpresultSetoverlap.forEach(element => {
if (element.length > 0) {
resultSetoverlap = [...resultSetoverlap, element];
}
});
return resultSetoverlap;
};
const min = 2;
//To handle overlapping issue in overlapping set, that casuing
overlap.forEach((key, idx) => {
if (idx < overlap.length - 1) {
for (let i = idx + 1; i < overlap.length; i++) {
console.log(`key: ${key}`);
console.log(`search: ${overlap[i]}`);
let overlapSection = GetOverlappingSection(key, overlap[i], min);
if (overlapSection.length > 0) {
console.log(`overlapSection: ${overlapSection}`);
overlap[idx] = overlap[idx].replace(overlapSection, '');
}
}
}
});
overlap = removeEmptyKeyword(overlap);
console.log(overlap);
overlap.forEach(key => {
keywordSet2 = keywordSet2.map((k1, idx) => {
console.log(`checking overlap keyword:'${key}' in '${k1}'`);
return k1.replace(key, '');
});
});
overlap.forEach(key => {
keywordSet1 = keywordSet1.map((k1, idx) => {
console.log(`checking overlap keyword:'${key}' in '${k1}'`);
return k1.replace(key, '');
});
});
keywordSet2 = removeEmptyKeyword(keywordSet2);
keywordSet1 = removeEmptyKeyword(keywordSet1);
overlap.forEach(key => {
text = text.replace(key, `$#k1k2$&$`);
});
keywordSet1.forEach(key => {
text = text.replace(key, `$#k1$&$`);
});
keywordSet2.forEach(key => {
text = text.replace(key, `$#k2$&$`);
});
console.log(`ResultSetoverlap after processing:${text}`);
Because I need to decompress and I find these logic puzzles fun, here's my solution to the problem...
https://highdex.net/begin_end_overlap.htm
You can view source of the page to see JavaScript code I used. But just in case I ever take that page down, here's the important function...
function GetOverlappingSection(str1, str2, minOverlapLen = 4) {
var work1 = str1;
var work2 = str2;
var w1Len = work1.length;
var w2Len = work2.length;
var resultStr = "";
var foundResult = false;
var workIndex;
if (minOverlapLen < 1) { minOverlapLen = 1; }
else if (minOverlapLen > (w1Len > w2Len ? w2Len : w1Len)) { minOverlapLen = (w1Len > w2Len ? w2Len : w1Len); }
//debugger;
//we have four loops to go through. We trim each string down from each end and see if it matches either end of the other string.
for (var i1f = 0; i1f < w1Len; i1f++) {
workIndex = work2.indexOf(work1);
if (workIndex == 0 || (workIndex != -1 && workIndex == w2Len - work1.length)) {
//we found a match!
foundResult = true;
resultStr = work1;
break;
}
work1 = work1.substr(1);
if (work1.length < minOverlapLen) { break; }
}
if (!foundResult) {
//debugger;
//reset the work vars...
work1 = str1;
for (var i1b = 0; i1b < w1Len; i1b++) {
workIndex = work2.indexOf(work1);
if (workIndex == 0 || (workIndex != -1 && workIndex == w2Len - work1.length)) {
//we found a match!
foundResult = true;
resultStr = work1;
break;
}
work1 = work1.substr(0, work1.length - 1);
if (work1.length < minOverlapLen) { break; }
}
}
if (!foundResult) {
//debugger;
//reset the work vars...
work1 = str1;
for (var i2f = 0; i2f < w2Len; i2f++) {
workIndex = work1.indexOf(work2);
if (workIndex == 0 || (workIndex != -1 && workIndex == w1Len - work2.length)) {
//we found a match!
foundResult = true;
resultStr = work2;
break;
}
work2 = work2.substr(1);
if (work2.length < minOverlapLen) { break; }
}
}
if (!foundResult) {
//debugger;
//reset the work vars...
work2 = str2;
for (var i2b = 0; i2b < w2Len; i2b++) {
workIndex = work1.indexOf(work2);
if (workIndex == 0 || (workIndex != -1 && workIndex == w1Len - work2.length)) {
//we found a match!
foundResult = true;
resultStr = work2;
break;
}
work2 = work2.substr(0, work2.length - 1);
if (work2.length < minOverlapLen) { break; }
}
}
return resultStr;
}
Hopefully that's helpful.

No response from recursive function

I want to create a function that is able to determine if a number is same or palindrome. if a given number is palindrome or same then return 2 otherwise if it is not palindrome or same then i need check it twice by increment the given number by 1. after that if it palindrome or same then return 1. if no palindrome or same number found then return 0. i write the function which is giving me the exact result when i give the number as 11211 but the function don't show any response if i enter 1122 or other random value. please help me to find where the error of my function.
function sameOrPalindrome(num) {
var c = 0;
var al = 0;
var normalArray = num.toString().split("");
var revArray = num.toString().split("").reverse();
for (var i = 0; i < normalArray.length; i++) {
if (normalArray[i] != revArray[i]) {
c++;
}
}
if (c == 0) {
return 2;
} else {
num++;
al = sameOrPalindrome(num);
if (al == 2) {
return 1;
} else {
num++;
al = sameOrPalindrome(num);
if (al == 2) {
return 1;
}
}
}
return 0;
}
console.log("1233",sameOrPalindrome(1233))
here is my solution to this problem:
function reversedNum(num) {
return (
parseFloat(
num
.toString()
.split('')
.reverse()
.join('')
) * Math.sign(num)
)
}
function sameOrPalindrome(num) {
if (num === reversedNum(num)) {
return 2;
} else {
num++;
if (num === reversedNum(num)) {
return 1;
} else {
num++;
if (num === reversedNum(num)) {
return 1;
}
}
}
return 0;
}
console.log("1233",sameOrPalindrome(1233))
Perhaps not using recurse - I think your function loops
const allEqual = arr => arr.every( v => v === arr[0] )
const sameOrPalin = num => {
const str = String(num);
let arr = str.split("")
if (allEqual(arr)) return 2
arr.reverse();
if (arr.join("") === str) return 1;
return 0
};
console.log("1111",sameOrPalin(1111));
console.log("2111",sameOrPalin(2111));
console.log("2112",sameOrPalin(2112));
console.log("1234",sameOrPalin(1234));
for (let i = 2111; i<=2113; i++) console.log(i,sameOrPalin(i));
Question: I assumed if palindrome test is true at first time then return 2. if not try incrementing by one and test the palindrome again . if true return 1 else try incrementing for last time and check the palindrome if true return 1 else 0.
Store string into array first and do arr.reverse().join("") to compare
let arr=num.toString().split("");
if(num.toString() == arr.reverse().join(""))
function sameOrPalindrome(num, times) {
let arr = num.toString().split("");
if (num.toString() == arr.reverse().join("")) {
if (times == 3) return 2
else return 1;
} else if (times > 0) {
num++; times--;
return sameOrPalindrome(num, times);
} else return 0
}
console.log(sameOrPalindrome(123321, 3));
console.log(sameOrPalindrome(223321, 3));
console.log(sameOrPalindrome(323321, 3));
Your function needs to know if it should not call itself any more, e.g. when it's doing the second and third checks:
function sameOrPalindrome(num,stop) { // <-- added "stop"
var c = 0;
var al = 0;
var normalArray = num.toString().split("");
var revArray = num.toString().split("").reverse();
for (var i = 0; i < normalArray.length; i++) {
if (normalArray[i] != revArray[i]) {
c++;
}
}
if (c == 0) {
return 2;
} else if(!stop) { // <-- check of "stop"
num++;
al = sameOrPalindrome(num,true); // <-- passing true here
if (al == 2) {
return 1;
} else {
num++;
al = sameOrPalindrome(num,true); // <-- and also here
if (al == 2) {
return 1;
}
}
}
return 0;
}
for(let i=8225;i<8230;i++)
console.log(i,sameOrPalindrome(i));
function check_palindrom(num){
var c1 = 0;
var normalArray = num.toString().split("");
var revArray = num.toString().split("").reverse();
for (var i = 0; i < normalArray.length; i++) {
if (normalArray[i] == revArray[i]) {
c1++;
}
}
if(c1==0){
return 2;
}else{
return 1;
}
}//check_palindrom
function my_fun_check_palindrome(mynum){
//console.log(mynum);
var num = mynum;
var c2 = 0;
var al = 0;
var normalArray = mynum.toString().split("");
var revArray = mynum.toString().split("").reverse();
for (var j = 0; j < normalArray.length; j++) {
if (normalArray[j] == revArray[j]) {
c2++;
}
}
if(c2==0){
console.log('Number is palindrome. Return Value :'+ 2);
}
if(1){
console.log('checking again with incremeting value my one');
num = parseInt(num)+1;
al = check_palindrom(num);
if(al==2){
console.log('Number is palindrome. Return Value :'+ 1);
}else{
console.log('Number is not palindrome. Return Value :'+ 0);
}
}
}//my_fun_check_palindrome
console.log(my_fun_check_palindrome(1122));
console.log(my_fun_check_palindrome(11221));
We should always strive to make function more effiecient... you dont need to run full loop. plus actual checking of palindrome can me modularized
function isSameOrPalindrome(num) {
var normalArray = num.toString().split("");
var revArray = num.toString().split("").reverse(),
i;
for (i = 0; i < normalArray.length / 2; i++) {
if (normalArray[i] !== revArray[i]) {
break;
}
}
if (i >= normalArray.length/2) {
return "Palindrome";
} else {
return "Not Palindrome";
}
}
function doCheck(num) {
var isPalindrome = isSameOrPalindrome(num);
console.log(isPalindrome);
if(isPalindrome === "Palindrome") {
return 2;
} else {
num++;
isPalindrome = isSameOrPalindrome(num);
if(isPalindrome === "Palindrome") {
return 1;
} else {
return 0
}
}
}
console.log("100",doCheck(100));

Math.pow returning 0 in calc

I'm making a calculator currently and I'm running into an issue with one of the functions, specifically x^y, it keeps returning 0 and not even seeming to run the setInterval at all, though it runs without the if function around it. fn is for which function its using which is x^y, and vi is just a tool in the calculator to distinguish which number you are changing as in reactant, or reactant2, reactants are the 2 numbers that are squared against each other in this case. (this is only the portion of the code with the problem)
function click15(){
if (reactant > 0) {
reactant = parseFloat(reactant);
}
if (reactant2 > 0) {
reactant2 = parseFloat(reactant2);
}
if (fn === 0) {
product = reactant / reactant2;
} else if (fn === 1) {
product = reactant * reactant2;
} else if (fn === 2) {
product = reactant - reactant2;
} else if (fn === 3) {
product = reactant + reactant2;
} else if (fn === 4) {
if (vi === 0) {
vi = 1;
var timer = setInterval(function(){
if (vi === 0) {
product = (Math.pow(reactant, reactant2));
clearInterval(timer);
}
}, 4);
}
}
reactant = product;
product = 0;
reactant2 = "0";
vir = 0;
vir2 = 0;
vi = 0;
di1 = 0;
di2 = 0;
fn = -1;
}

Variable only works locally

I wrote some functions involving prime factorization and I noticed that when I identified my test paragraph (for testing the results of functions and such) as document.getElementById("text"), it worked fine. However, when I declared a global variable text as var text = document.getElementById("text"), and then substituted in text for the longer version, it no longer worked. I did, however, notice that it worked when I locally declared text. Why is this and how can I fix it? My JSFiddle is here: https://jsfiddle.net/MCBlastoise/3ehcz214/
And this is my code:
var text = document.getElementById("text");
function isPrime(num) {
var lastDigit = parseInt((num + "").split("").reverse()[0]);
if (typeof num !== "number" || num <= 1 || num % 1 !== 0) {
return undefined;
}
else if (num === 2) {
return true;
}
else if (lastDigit === 0 || lastDigit === 2 || lastDigit === 4 || lastDigit === 5 || lastDigit === 6 || lastDigit === 8) {
return false;
}
else {
for (var i = 2; i < num; i++) {
if (num % i === 0) {
return false;
}
}
return true;
}
}
function factorSplit(dig) {
if (typeof dig !== "number" || dig <= 1 || dig % 1 !== 0) {
return undefined;
}
else if (dig === 2) {
return undefined;
}
else {
var factor;
for (var i = 2; i < dig; i++) {
if (dig % i === 0) {
factor = i;
break;
}
}
if (factor === undefined) {
return undefined;
}
else {
return [factor, (dig / factor)];
}
}
}
function allPrimes(arr) {
if (Array.isArray(arr) === false || arr.length < 1) {
return undefined;
}
else {
for (var i = 0; i < arr.length; i++) {
if (isPrime(arr[i]) !== true) {
return false;
}
}
return true;
}
}
function primeFactors(int) {
if (typeof int !== "number" || int <= 1) {
return undefined;
}
else if (isPrime(int) === true) {
return false;
}
else {
var initFactors = factorSplit(int);
while (allPrimes(initFactors) !== true) {
initFactors = initFactors.concat(factorSplit(initFactors[initFactors.length - 1]));
initFactors.splice((initFactors.length - 3), 1);
}
return initFactors;
}
}
function listPrimes() {
repeat = setInterval(findPrime, 1);
}
var primeInts = [2];
var check;
function findPrime() {
var i = primeInts[primeInts.length - 1] + 1;
if (check === undefined) {
check = true;
text.innerHTML = primeInts[0];
}
else {
while (isPrime(i) !== true) {
i++;
}
primeInts.push(i);
text.innerHTML += ", " + primeInts[primeInts.length - 1];
}
}
//text.innerHTML = isPrime(6);
<div onclick="listPrimes()" style="cursor:pointer; background-color:black; width:30px; height:30px"></div>
<p id="text"></p>
The text is global, you just need to make sure the whole script file is included in the html. Here's an example of what I mean
Here in code snippets stackoverflow does this for us already.
var text = document.getElementById("text");
function isPrime(num) {
var lastDigit = parseInt((num + "").split("").reverse()[0]);
if (typeof num !== "number" || num <= 1 || num % 1 !== 0) {
return undefined;
} else if (num === 2) {
return true;
} else if (lastDigit === 0 || lastDigit === 2 || lastDigit === 4 || lastDigit === 5 || lastDigit === 6 || lastDigit === 8) {
return false;
} else {
for (var i = 2; i < num; i++) {
if (num % i === 0) {
return false;
}
}
return true;
}
}
function factorSplit(dig) {
if (typeof dig !== "number" || dig <= 1 || dig % 1 !== 0) {
return undefined;
} else if (dig === 2) {
return undefined;
} else {
var factor;
for (var i = 2; i < dig; i++) {
if (dig % i === 0) {
factor = i;
break;
}
}
if (factor === undefined) {
return undefined;
} else {
return [factor, (dig / factor)];
}
}
}
function allPrimes(arr) {
if (Array.isArray(arr) === false || arr.length < 1) {
return undefined;
} else {
for (var i = 0; i < arr.length; i++) {
if (isPrime(arr[i]) !== true) {
return false;
}
}
return true;
}
}
function primeFactors(int) {
if (typeof int !== "number" || int <= 1) {
return undefined;
} else if (isPrime(int) === true) {
return false;
} else {
var initFactors = factorSplit(int);
while (allPrimes(initFactors) !== true) {
initFactors = initFactors.concat(factorSplit(initFactors[initFactors.length - 1]));
initFactors.splice((initFactors.length - 3), 1);
}
return initFactors;
}
}
function listPrimes() {
repeat = setInterval(findPrime, 1);
}
var primeInts = [2];
var check;
function findPrime() {
var i = primeInts[primeInts.length - 1] + 1;
if (check === undefined) {
check = true;
text.innerHTML = primeInts[0];
} else {
while (isPrime(i) !== true) {
i++;
}
primeInts.push(i);
text.innerHTML += ", " + primeInts[primeInts.length - 1];
}
}
function test() {
console.log("inside test1")
console.log(text);
text.innerHTML = "testtt"
}
function test2() {
console.log("inside test2")
console.log(text);
text.innerHTML = "testtt2"
}
text.innerHTML = isPrime(6);
<div onclick="test()" style="cursor:pointer; background-color:black; width:30px; height:30px"></div>
<p id="text"></p>
<div onclick="test2()" style="cursor:pointer; background-color:black; width:30px; height:30px"></div>
In the head the script runs/loads first and because you don't have the var's in a function they are never re-used they remain with the original value which is null since the document didn't exist at that time, then when the page loads all it has is access to the functions a call to the global var is null. This is why the code previously only worked when text = document.getElementById('text') was in a function.

Stacks with Javascript

I am working with stacks on the infamous 'Braces' problem and I got to a halt. This should be an easy fix but my eyes are not much of a help at the moment.
The first call to the function is working like a charm but the second one is running an extra time and I can't see why.
The first call returns 01110 which is correct but the second returns 011110 which is not...
If you can't read the code here, got to the fiddle
//constructor function for our Stack class
function Stack() {
this.dataStore = [];
this.top = 0;
this.push = push;
this.pop = pop;
this.peek = peek;
this.length = length;
this.clear = clear;
}
function push(element) {
this.dataStore[this.top++] = element;
}
function pop() {
return this.dataStore[--this.top];
}
function peek() {
return this.dataStore[this.top - 1];
}
function length() {
return this.top;
}
function clear() {
this.top = 0;
}
function braces(expression) {
for (var i = 0; i < expression.length; i++) {
//if the number of elements in the expression is odd, it is guaranteed not to have a matching expression
//therefore we print 0
if (expression[i].length%2 !== 0) {
console.log(0);
} else {
var s = new Stack();
var startPoint = expression[i].charAt(0);
//if the expression starts with an open brace it means we will not have a matching expression so we print 0
if (startPoint == '(' || startPoint == '{' || startPoint == '[') {
for (var j = 0; j < expression[i].length; j++) {
var char = expression[i].charAt(j);
var h = '';
if (char == '(' || char == '{' || char == '[') {
s.push(char);
} else {
h = s.peek();
if (h == "(" && char == ")") {
s.pop();
} else if (h == "{" && char == "}") {
s.pop();
} else if (h == "[" && char == "]") {
s.pop();
}
}
}
} else {
console.log(0);
}
if (s.length() == 0) {
console.log(1)
} else {
console.log(0);
}
}
}
}
var expr = [ "}()()", "[]({})", "([])", "{()[]}", "([)]" ]; //working
var expr2 = [ "}()(){", "[]({})", "([])", "{()[]}", "([)]" ]; //running an extra time
braces(expr);
Change this:
else {
console.log(0);
continue; //this is new
}
if (s.length() == 0) {
Your function would log both 0 and 1/0 if the startpoint is not { or ( or [ and the length of s was 0
Your stack functions are all outside of the scope of Stack() and therefore the data probably won't be what you expect. You can start fixing this by putting functions inside the Stack() function:
function Stack() {
this.dataStore = [];
this.top = 0;
this.push = push;
this.pop = pop;
this.peek = peek;
this.length = length;
this.clear = clear;
this.pop = function () {
// pop
}
this.push = function () {
// code
}
this.peek = function () {
// code
}
}
That way, the methods all have access to the same data.

Categories

Resources