Async function in javascript stops executing all by itself - javascript

Here I have an async function in javascript that is used to fill up the sudoku board with numbers (basically its solution). I used a sleeper function between each number insertion so that the user can get a better feel of the recursion and backtracking algorithm, however after the fifteenth number gets inserted, the function stops by itself... What is going on here exactly ?
var finalInd;
function sleep() {
console.log("happy")
return new Promise(resolve => setTimeout(resolve, 100));
}
async function solve () {
allowed = false;
var empty = findEmptySpace();
if(!empty) {
return true;
}
for(let i=1; i<10; i++) {
if(checkDuplicates(board, i, empty)) {
board[empty[0]][empty[1]] = i;
finalInd = (empty[0]*9) + empty[1];
await sleep()
funcId("board").children[finalInd].innerHTML = i;
if(solve(board)) {
return true;
}
board[empty[0]][empty[1]] = 0;
funcId("board").children[finalInd].innerHTML = 0;
}
}
funcId("board").children[0].innerHTML = board[0][0];
return false;
}
function checkDuplicates (board, num, empty) {
for(let i=0; i<9; i++) {
if(board[empty[0]][i] == num && empty[1] != i) {
return false;
}
}
for(let i=0; i<9; i++) {
if(board[i][empty[1]] == num && empty[0] != i) {
return false;
}
}
var x = Math.floor(empty[1]/3);
var y = Math.floor(empty[0]/3);
for(let i=(y*3); i<(y*3)+3; i++) {
for(let j=(x*3); j<(x*3)+3; j++) {
if(board[i][j] == num && i != empty[0] && j != empty[1]) {
return false;
}
}
}
return true;
}
function findEmptySpace () {
for(let i=0; i<9; i++) {
for(let j=0; j<9; j++) {
if(board[i][j] == 0) {
return [i, j];
}
}
}
}

I think you forgot to await the recursive call to solve, so it will always return a promise, which it's truthy, and your function will terminate.

Related

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));

What the meaning of return [''] in JavaScript?

Please see this leetcode solution. In the function it returns [''] which actually return an array of answer. Could someone tell me what's going on there?
[The problem is solved. Actually it will return in the middle of the code.]
https://leetcode.com/problems/remove-invalid-parentheses/discuss/154272/JavaScript-BFS-solution
function removeInvalidParentheses(s) {
let queue = new Set([s]);
while (queue.size) {
const next = new Set();
for (let v of queue) {
if (isValid(v)) {
return [...queue].filter(isValid);
}
for (let i = 0; i < v.length; i++) {
next.add(v.slice(0, i) + v.slice(i+1));
}
}
queue = next;
}
return [''];
}
function isValid(str) {
let bal = 0;
for (let ch of str) {
if (ch === '(') {
bal++;
} else if (ch === ')') {
bal--;
}
if (bal < 0) {
return false;
}
}
return bal === 0;
}
The function returns an array with a single empty string if the prior code (line 7) does not return a result. It is simply a default value so that calling code sees some result from the method.
function removeInvalidParentheses(s) {
let queue = new Set([s]);
while (queue.size) {
const next = new Set();
for (let v of queue) {
if (isValid(v)) {
return [...queue].filter(isValid);
}
for (let i = 0; i < v.length; i++) {
next.add(v.slice(0, i) + v.slice(i+1));
}
}
queue = next;
}
return [''];
}
function isValid(str) {
let bal = 0;
for (let ch of str) {
if (ch === '(') {
bal++;
} else if (ch === ')') {
bal--;
}
if (bal < 0) {
return false;
}
}
return bal === 0;
}

Javascript 'for' loop works incorrect when i put 'if' in it. What am i doing wrong?

var i;
function f_arrsmatch (array1,array2) {
var error = 0;
if(!array1 || !array2) { error++; }
if(array1.length != array2.length) { error++; }
for (i = 0; i < array1.length; i++) {
if(array1[i] instanceof Array && array2[i] instanceof Array) {
if(!f_arrsmatch(array1[i], array2[i])) { error++; }
} else {
if(array1[i] != array2[i]) { error++; }
}
}
return (error == 0);
}
var arr1 = [1,2,3];
var arr2 = [[3,1,2],[1,3,2],[3,2,1]];
for(i = 0; i < arr2.length; i++) {
if(f_arrsmatch(arr1, arr2[i])) {
alert('true');
} else {
alert('false');
}
}
It shows alert with 'false' text only 1 time, but if I run this:
var i;
function f_arrsmatch (array1,array2) {
var error = 0;
if(!array1 || !array2) { error++; }
if(array1.length != array2.length) { error++; }
for (i = 0; i < array1.length; i++) {
if(array1[i] instanceof Array && array2[i] instanceof Array) {
if(!f_arrsmatch(array1[i], array2[i])) { error++; }
} else {
if(array1[i] != array2[i]) { error++; }
}
}
return (error == 0);
}
var arr1 = [1,2,3];
var arr2 = [[3,1,2],[1,3,2],[3,2,1]];
for(i = 0; i < arr2.length; i++) {
alert('something');
}
then browser alerts 3 times with text 'something'. Is it okay for js to be so weird or am i doing something wrong?
In function f_arrsmatch, the global variable i is re-evaluated. After the call of f_arrsmatch, the i is assigned as 3. Then to the next step of loop, the condition i < arr2.length is false, so the loop finish, thus the alert will be called only one time.

tic-tac-toe: different output while using 1d-array over 2d- array

I am trying to build tic-tac-toe AI using min max algorithm. I was referring to this post from geekforgeeks for writing my code. But strangely when I'm using 1D array instead of 2D array by modifying the code as given below, I'm not getting the right output from findBestMove function. It is supposed to return index as 4, but it always returns 2. what am I doing wrong?
function Move(x,y){
this.row = x,
this.col = y;
};
const player = 'o', opponent = 'x';
const isMovesLeft = (board) => {
for (let i = 0; i<3; i++)
for (let j = 0; j<3; j++)
if (board[i][j]=='_')
return true;
return false;
}
const isMovesLeft2 = (board) => {
for (let i = 0; i<9; i++)
if (board[i]=='_')
return true;
return false;
}
const evaluate = (b) =>{
for (let row = 0; row<3; row++)
{
if (b[row][0]==b[row][1] &&
b[row][1]==b[row][2])
{
if (b[row][0]==player)
return +10;
else if (b[row][0]==opponent)
return -10;
}
}
for (let col = 0; col<3; col++)
{
if (b[0][col]==b[1][col] &&
b[1][col]==b[2][col])
{
if (b[0][col]==player)
return +10;
else if (b[0][col]==opponent)
return -10;
}
}
if (b[0][0]==b[1][1] && b[1][1]==b[2][2])
{
if (b[0][0]==player)
return +10;
else if (b[0][0]==opponent)
return -10;
}
if (b[0][2]==b[1][1] && b[1][1]==b[2][0])
{
if (b[0][2]==player)
return +10;
else if (b[0][2]==opponent)
return -10;
}
return 0;
}
const evaluate2 = (b) =>{
for (let row = 0; row<3; row++)
{
if (b[row]==b[row+1] &&
b[row+1]==b[row+2])
{
if (b[row]==player)
return +10;
else if (b[row]==opponent)
return -10;
}
}
for (let col = 0; col<3; col++)
{
if (b[col]==b[col+3] &&
b[col+3]==b[col+6])
{
if (b[col]==player)
return +10;
else if (b[col]==opponent)
return -10;
}
}
if (b[0]==b[4] && b[4]==b[8])
{
if (b[0]==player)
return +10;
else if (b[0]==opponent)
return -10;
}
if (b[2]==b[4] && b[4]==b[6])
{
if (b[2]==player)
return +10;
else if (b[2]==opponent)
return -10;
}
return 0;
}
const minimax = (board , depth, isMax) => {
let score = evaluate(board);
if (score == 10)
return score;
if (score == -10)
return score;
if (isMovesLeft(board)==false)
return 0;
if (isMax)
{
let best = -1000;
for (let i = 0; i<3; i++)
{
for (let j = 0; j<3; j++)
{
if (board[i][j]=='_')
{
board[i][j] = player;
best = Math.max( best,
minimax(board, depth+1, !isMax) );
board[i][j] = '_';
}
}
}
return best;
}
else
{
let best = 1000;
// Traverse all cells
for (let i = 0; i<3; i++)
{
for (let j = 0; j<3; j++)
{
if (board[i][j]=='_')
{
board[i][j] = opponent;
best = Math.min(best,
minimax(board, depth+1, !isMax));
board[i][j] = '_';
}
}
}
return best;
}
}
const minimax2 = (board , depth, isMax) => {
let score = evaluate2(board);
if (score == 10)
return score;
if (score == -10)
return score;
if (isMovesLeft2(board)==false)
return 0;
if (isMax)
{
let best = -1000;
for (let i = 0; i<9; i++)
{
if (board[i]=='_')
{
board[i] = player;
best = Math.max( best,
minimax2(board, depth+1, !isMax) );
board[i] = '_';
}
}
return best;
}
else
{
let best = 1000;
for (let i = 0; i<9; i++)
{
if (board[i]=='_')
{
board[i] = opponent;
best = Math.min(best,
minimax2(board, depth+1, !isMax));
board[i] = '_';
}
}
return best;
}
}
const findBestMove = (board) =>{
let bestVal = -1000;
let bestMove = new Move(-1,-1);
for (let i = 0; i<3; i++)
{
for (let j = 0; j<3; j++)
{
if (board[i][j]=='_')
{
board[i][j] = player;
let moveVal = minimax(board, 0, false);
board[i][j] = '_';
if (moveVal > bestVal)
{
bestMove.row = i;
bestMove.col = j;
bestVal = moveVal;
}
}
}
}
return bestMove;
}
const findBestMove2 = (board) =>{
let bestVal = -1000;
let bestMove = -1;
for (let i = 0; i<9; i++)
{
if (board[i]=='_')
{
board[i] = player;
let moveVal = minimax2(board, 0, false);
board[i]= '_';
if (moveVal > bestVal)
{
bestMove = i
bestVal = moveVal;
}
}
}
return bestMove;
}
const test = () => {
const board = [['x','_','_'],
['_','_','_'],
['_','_','_']];
const board2 = ['x','_','_',
'_','_','_',
'_','_','_'];
console.log(findBestMove(board));
console.log(findBestMove2(board2));
}
test();
When the test() is executed first function call returns best move as (1,1) but second function returns 2. It should be 4 ideally.
In function evaluate2, you loop like this:
for (let row = 0; row<3; row++)
You should loop like this
for (let row = 0; row<9; row+=3)

called function refuses to return true

Even when sum === largest in subset(), I don't get a "true" in my console. The true is sent back only to the calling function? Then how do I get the "return true" to behave as a newbie would expect?
function ArrayAdditionI(arr)
{
arr.sort();
var largest = arr.pop()
subset([], arr, largest);
}
function subset(soFar, rest, largest)
{
var sum = 0;
if (rest.length === 0)
{
for(var i=0; i<soFar.length; i++)
{
sum+= soFar[i];
}
if (sum === largest)
{
return true;
}
}
else
{
var soFar2 = soFar.slice(0);
soFar2.push(rest[0]);
subset(soFar,rest.slice(1),largest);
subset(soFar2, rest.slice(1),largest);
}
}
ArrayAdditionI([85,3,88,2])
function ArrayAdditionI(arr)
{
arr.sort();
var largest = arr.pop()
var ret = subset([], arr, largest);
// do something with ret
}
function subset(soFar, rest, largest)
{
var sum = 0;
if (rest.length === 0)
{
for(var i=0; i<soFar.length; i++)
{
sum+= soFar[i];
}
if (sum === largest)
{
return true;
}
}
else
{
var soFar2 = soFar.slice(0);
soFar2.push(rest[0]);
subset(soFar,rest.slice(1),largest);
subset(soFar2, rest.slice(1),largest);
}
return false;
}
ArrayAdditionI([85,3,88,2])

Categories

Resources