How to create a pause in recursion function loop - javascript

I'm new here so sorry if dublicate.
I'm trying to write a sudoku solver using backtracking method to make it pass all data dynamically into the document with its each recursion. When I tried to use setInterval() or setTimeout() it doesn't work the way I want it to work. What I need should be similar to this
Here's the code:
function backtrack(position) {
if (position === 81) {
return true;
}
if (sudokuArray[position] > 0) {
backtrack(position + 1);
} else {
for (var x = 1; x <= 9; x++) {
if (isValid(x, parseInt(position / 9), position % 9) === true) {
sudokuArray[position] = x;
//some code that invokes putSudokuArrayBack function with a small delay
//everytime backtrack function is invoked
if (backtrack(position + 1) === true) {
return true;
}
}
}
sudokuArray[position] = 0;
return false;
}
}
function putSudokuArrayBack() {
for (var i = 0; i <= 81; i++) {
var indexString = '#val-' + parseInt(i / 9) + '-' + i % 9;
$(indexString).val(sudokuArray[i]);
}
}
Any ideas(if it's even possible)? Thanks in advance!

Related

Jquery if value <= something dont working

Help me please to understand why not working that part of code.
I'm trying to style a block depending on a variable, but that part doesn't work.
var starsrating = 3;
function markstars() {
if (jQuery(starsrating).val() >= 1) {
jQuery("div.rating-star1").addClass("rating-star-active");
console.log("1");
}
if (jQuery(starsrating).val() >= 2) {
jQuery("div.rating-star1, div.rating-star2").addClass("rating-star-active");
console.log("2");
}
if (jQuery(starsrating).val() >= 3) {
jQuery("div.rating-star1, div.rating-star2, div.rating-star3").addClass("rating-star-active");
console.log("3");
}
if (jQuery(starsrating).val() >= 4) {
jQuery("div.rating-star1, div.rating-star2, div.rating-star3, div.rating-star4").addClass("rating-star-active");
console.log("4");
}
if (jQuery(starsrating).val() >= 5) {
jQuery("div.rating-star1, div.rating-star2, div.rating-star3, div.rating-star4, div.rating-star5").addClass("rating-star-active");
console.log("5");
}
console.log("end of func");
}
markstars();
starsrating is a plain number; you can't call jQuery on it.
A further simplification is to loop over all numbers 1..5 and set the states of the divs programmatically:
function markstars(starsrating) {
for (var i = 1; i <= 5; i++) {
jQuery("div.rating-star" + i).toggleClass("rating-star-active", starsrating >= i);
}
}
markstars(3);

JavaScript Recursive function return undefined instead of an array

I have the next function:
function solveSudoku(prev_tab, fila, columna) {
let tab = _.cloneDeep(prev_tab);
let sig_fila = fila;
let sig_col = columna;
if (fila === 8 && columna === 8) {
//console.log(tab);
return tab;
}
if (columna === 8) {
sig_col = 0;
sig_fila = sig_fila + 1
} else {
sig_col = sig_col + 1;
}
if ((tab[fila][columna]) !== '') {
solveSudoku(tab, sig_fila, sig_col)
} else {
for (let num = 1; num <= 9; num++) {
if (numeroValido(tab, num, fila, columna)) {
tab[fila][columna] = num;
//tab.toString();
solveSudoku(tab, sig_fila, sig_col)
}
}
}
}
it returns undefined instead of a 2D array, i already try to add return in every recursive call =>
return solveSudoku( tab, sig_fila, sig_col )
but now that doesn't work either
I'm not really familiar with algorithms for solving sudoku, so I don't know if the algorithm below is correct.
But you need to ensure that the result of the recursion is returned. In my update below, I return the first recursive call. In the loop, I only return it if the recursion successfully found a solution, otherwise the loop continues trying other numbers in the column.
function solveSudoku(prev_tab, fila, columna) {
let tab = _.cloneDeep(prev_tab);
let sig_fila = fila;
let sig_col = columna;
if (fila === 8 && columna === 8) {
//console.log(tab);
return tab;
}
if (columna === 8) {
sig_col = 0;
sig_fila = sig_fila + 1
} else {
sig_col = sig_col + 1;
}
if ((tab[fila][columna]) !== '') {
return solveSudoku(tab, sig_fila, sig_col)
} else {
for (let num = 1; num <= 9; num++) {
if (numeroValido(tab, num, fila, columna)) {
tab[fila][columna] = num;
//tab.toString();
let result = solveSudoku(tab, sig_fila, sig_col);
if (result) { // continue searching if the recursion failed
return result;
}
}
}
}
}

Stop recursive setTimeout function

Im running a recursive setTimeout function and I can run it many times, it has a clearTimeout, with this property I can handle how to stop the function running.
But I can't figure out how to stop it in another function.
var a = 0;
var b = 0;
function Listener(x, y) {
var lValue = y == true ? a : b;
if (lValue < 100) {
console.log(lValue);
if(y == true){
a+=x;
}else{
b+=x;
}
setTimeout(Listener.bind(this, x, y), 1000);
} else {
clearTimeout(Listener);
if(y == true){
a=0;
}else{
b=0;
}
}
}
When i tried to run it twice, it works:
My doubt is: How can I stop a particular running instance.
A couple notes:
Given the constant timeout of 1000, you should be using setInterval() instead. It will greatly simplify your function, and allow you to cancel the interval whenever you want.
Using global variables is code smell, create an object instead to hold a reference to the value being incremented. Doing so will also allow your function parameters to be more intuitive.
Here's a solution incorporating these two suggestions:
function range (step, start = 0, stop = 100) {
const state = {
value: start,
interval: setInterval(callback, 1000)
};
function callback () {
if (state.value < stop) {
console.log(state.value);
state.value += step;
} else {
console.log('timer done');
clearInterval(state.interval);
}
}
callback();
return state;
}
const timer1 = range(10);
const timer2 = range(20);
setTimeout(() => {
console.log('stopping timer 1');
clearInterval(timer1.interval);
}, 2500);
setTimeout(() => {
console.log('timer 2 value:', timer2.value);
}, 3500);
You could elevate the timer to a higher scope that is accessible by other functions.
var a = 0;
var b = 0;
var timer = null;
function Listener(x, y) {
var lValue = y == true ? a : b;
if (lValue < 100) {
console.log(lValue);
if (y == true) {
a += x;
} else {
b += x;
}
timer = setTimeout(Listener.bind(this, x, y), 1000);
} else {
clearTimeout(timer);
if (y == true) {
a = 0;
} else {
b = 0;
}
}
}
function clearTimer() {
if (timer !== null) clearTimeout(timer);
}
Listener(3, 3);
// clear the timer after 3 secnods
setTimeout(clearTimer, 3000);
create a variable and store the reference of setTimout on that variable, after that you just clearTimout with that variable reference
e.x
GLOBAL VARIABLE:
var k = setTimeout(() => { alert(1)}, 10000)
clearTimeout(k)
var a = 0;
var b = 0;
var recursiveFunctionTimeout = null;
function Listener(x, y) {
var lValue = y == true ? a : b;
if (lValue < 100) {
console.log(lValue);
if(y == true){
a+=x;
}else{
b+=x;
}
recursiveFunctionTimeout = setTimeout(Listener.bind(this, x, y), 10);
} else {
clearTimeout(recursiveFunctionTimeout);
if(y == true){
a=0;
}else{
b=0;
}
}
}
LOCAL VARIABLE:
var a = 0;
var b = 0;
function Listener(x, y) {
var lValue = y == true ? a : b;
var recursiveFunctionTimeout = null;
if (lValue < 100) {
console.log(lValue);
if(y == true){
a+=x;
}else{
b+=x;
}
recursiveFunctionTimeout = setTimeout(Listener.bind(this, x, y), 10);
} else {
clearTimeout(recursiveFunctionTimeout);
if(y == true){
a=0;
}else{
b=0;
}
}
}

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

How can I simplify this using Javascript or jQuery?

I have 4 vertical sliding panels and I am using the following code for it. Is there any way I can simplify the code?
$(".sliding-panels").click(function() {
var n = $(this).attr("number");
$(".panel" + n).toggleClass("panel-active");
if (n == 1) {
$(".panel2").toggleClass("panel-push-right");
$(".panel3").toggleClass("panel-push-right");
$(".panel4").toggleClass("panel-push-right");
}
else if (n == 2) {
$(".panel1").toggleClass("panel-push-left");
$(".panel3").toggleClass("panel-push-right");
$(".panel4").toggleClass("panel-push-right");
}
else if (n == 3) {
$(".panel1").toggleClass("panel-push-left");
$(".panel2").toggleClass("panel-push-left");
$(".panel4").toggleClass("panel-push-right");
}
else if (n == 4) {
$(".panel1").toggleClass("panel-push-left");
$(".panel2").toggleClass("panel-push-left");
$(".panel3").toggleClass("panel-push-left");
}
});
How about replacing the if statement with:
var i, toggle_class;
for (i = 1; i <= 4; ++i) {
if (i === n) { toggle_class = "panel-active"; }
else if (i < n) { toggle_class = "panel-push-left"; }
else /* i > n */ { toggle_class = "panel-push-right"; }
$(".panel" + i ).toggleClass(toggle_class);
}
This may be a bit of a stretch, but assuming all the elements have the same class (maybe it even is .sliding-panels?) and are in order, i.e.
<div class="panel1"></div>
<div class="panel2"></div>
<div class="panel3"></div>
...
you can do:
var $panels = $(".sliding-panels").click(function() {
var n = $(this).attr("number") - 1;
$panels.toggleClass(function(index) {
return index === n ?
'panel-active' :
(index < n ? 'panel-push-left' : 'panel-push-right');
});
});
Let jQuery handle the element traversal.

Categories

Resources