What is wrong with my recursive function? - javascript

This recursive function works perfectly when u and v are hardcoded numbers but the moment I subsitute them with letters it stops working and I don't get what the problem is.
function findPath(x,y,u,v) {
if(x < 1 || x > n || y < 1 || y > n) return false;
if(u < 1 || u > n || v < 1 || v > n) return false;
if(x == u && y == v) {
arr[u][v].className = 'marked';
return true;
}
if(arr[x][y].className != 'path')
return false;
else {
arr[x][y].className = 'marked';
if(findPath(x-1,y)) return true;
if(findPath(x+1,y)) return true;
if(findPath(x,y+1)) return true;
if(findPath(x,y-1)) return true;
}
arr[x][y].className = 'path';
}
drawGrid(n);
findPath(1,1,7,4);

Related

What is the difference between putting the variable "top" inside for loop and before?

var isValid = function (s) {
let stack = [];
for (let i = 0; i < s.length; i++) {
let top = stack[stack.length - 1];
if (s[i] === "(" || s[i] === "{" || s[i] === "[") {
stack.push(s[i]);
} else if (s[i] === ")" && top === "(" && stack.length !== 0) {
stack.pop();
} else if (s[i] === "]" && top === "[" && stack.length !== 0) {
stack.pop();
} else if (s[i] === "}" && top === "{" && stack.length !== 0) {
stack.pop();
} else {
return false;
}
}
return stack.length === 0;
};
Function like this works (this is the problem https://leetcode.com/problems/valid-parentheses/)
However when i put variable "top" before the for loop ,the function doest do its job.
Can you please explain me what is the difference in this 2 cases?
Thank you!
I tried to put variable "top" before and in the for loop ,got different acting function.

expected '0th' to equal '0'

function numberToOrdinal(i) {
var j = i % 10,
k = i % 100;
if (j == 0 && k == 100) {
return '0th';
}
if (j == 1 && k != 11) {
return i + "st";
}
if (j == 2 && k != 12) {
return i + "nd";
}
if (j == 3 && k != 13) {
return i + "rd";
}
return i + "th";
}
It's not passing this test, what's wrong?
should handle single digits
expected '0th' to equal '0'
if you gonna devide a unknown input you wanna check if the input given might be zero. Else there might be an devisionbyzero exception thrown.
function numberToOrdinal(i) {
if(i === 0){ // since we devide i we wanna check if it might be zero.
return i ;
}
var j = i % 10,
k = i % 100;
//if (j == 0 && k == 100) { didnt seem to be doing anything
//return '0th';
//}
if (j == 1 && k != 11) {
return i + "st";
}
if (j == 2 && k != 12) {
return i + "nd";
}
if (j == 3 && k != 13) {
return i + "rd";
}
return i + "th";
}
console.log(numberToOrdinal(0));
you could just change these lines
if (j == 0 && k == 100) {
return '0th';
}
to be
if (i == 0) {
return i
}
If you want your function to return 0 when 0 is passed to the function, you will need to enter a condition to handle that, such as:
if (i === 0) {
return 0;
}
You have to enter another condition to handle it
function numberToOrdinal(i) {
var j = i % 10,
k = i % 100;
if (i === 0) {
return i;
}
if (j == 1 && k != 11) {
return `${i}st`;
}
if (j == 2 && k != 12) {
return `${i}nd`;
}
if (j == 3 && k != 13) {
return `${i}rd`;
}
return `${i}th`;
}

Third if-clause can't be reached

This probably has an easy solution, but I simply don't see it at the moment.
I have three if-clauses that ashould be activated based on the length of an array. The first two ones seem to work fine, but for some odd reason I can't activate the third one (arr.length === 3). Right before the if clauses I have tried an alert to test whether it gives the right length of the array and it does.
function calculateDistances() {
var arr = [];
arr.push(posM, posL, posR);
alert(arr[1])
for (var i = 0; i < arr.length; i++) {
if (!arr[i]) {
arr.splice(i,1)
}
}
alert(arr.length)
if (arr.length === 0 || 1) {
return true;
}
else if (arr.length === 2 ) {
var diameter = calculateDiameter(arr[0], arr[1])
if (diameter > minDistance) {
return false;
}
else {
return true;
}
}
else if (arr.length === 3) {
alert("hello")
var diameter1 = calculateDiameter(arr[0], arr[1]);
var diameter2 = calculateDiameter(arr[0], arr[2]);
var diameter3 = calculateDiameter(arr[1], arr[3]);
if (diameter1 && diameter2 && diameter3 < minDistance) {
return true
}
else{
return false
}
}
}
Nor can you activate the second.
There's a bug here: if (arr.length === 0 || 1) {
The 1 casts to true.
Perhaps you meant: if (arr.length === 0 || arr.length === 1) {
You need this:
if (arr.length === 0 || arr.length === 1) {
The way you put it, it is equal to
if ((arr.length === 0) || true) {
which is always true.
I think what you are looking for is below condition in the first if condition
if (arr.length === 0 || arr.length === 1) {
return true;
}
this checks whether the length of the array is 1 or it's 0. Your first if condition is always true as it has 1 which is true.
(arr.length === 0 || 1)
is always true.
You could usethis instead
if (arr.length <= 1)
{
return true;
}

Compare 3 values - Show the highest

Doing a survey where a user picks :
A B or C
I then need to know if the user has picked Mostly A's, B's or C's.
I'm trying a few jQuery logics' but not having much luck, Due to expression expected error.
Is there a neater / better way to show purely which variable is the highest?
My current jQuery :
var count = 0;
var count_a = 0;
var count_b = 0;
var count_c = 0;
$('.radio-select').click(function()
{
var chosen_option = $(this).val();
if(chosen_option == 'a')
{
count++;
count_a ++;
}
if(chosen_option == 'b')
{
count++;
count_b ++;
}
if(chosen_option == 'c')
{
count++;
count_c ++;
}
check_numbers(count, count_a, count_b, count_c);
})
function check_numbers(count, a, b, c)
{
parseInt(a);
parseInt(b);
parseInt(c);
if(count == '8')
{
if ((a > b ) && (a > c))
{
alert("A is Highest");
}
if ((b > a ) && (b > c))
{
alert("B is Highest");
}
if(c > b) && (c > a))
{
alert("C is highest!");
}
}
}
jsFiddle Example
If you wanted a smaller way of doing it you could use inline if statements. Up to you if this is a better way, I like it though.
a = 5
b = 11
c = 6
console.log((a > b && a > c? a : (b > c ? b : c)))
Firstly you do not need to use parseInt() on a, b, c as they are already integers. And again count is an integer while you are comparing it to a string. This should work.
if(count == 8)
{
if ((a > b ) && (a > c))
{
alert("A is Highest");
}
else if ((b > a ) && (b > c))
{
alert("B is Highest");
}
else
{
alert("C is highest!");
}
You need to fetch the value returned by parseInt. Use it like: a = parseInt(a); and same for the other variables before comparing them in the if...else.
function check_numbers(count, a, b, c)
{
var x = parseInt(a),
y = parseInt(b),
z = parseInt(c);
if(count == 8)
{
var result = (x > y ? (x > z ? x : z) : (y > z ? y : z));
}
}
#StuBlackett you can consider adding the values and labels to an array then sorting Descending and returning the lable at the top.
function CompareIndexZero(a, b) {
if (a[0] < b[0]) return 1;
if (a[0] > b[0]) return -1;
return 0;
}
function myFunction() {
var count_a = 2;
var count_b = 5;
var count_c = 4;
var arrHighest = [];
arrHighest.push([count_a, "A"]);
arrHighest.push([count_b, "B"]);
arrHighest.push([count_c, "C"]);
arrHighest.sort(CompareIndexZero);
alert(arrHighest[0][1] + " is the highest");
}
Here is a modified version of check_numbers() that works as intended if I got you right. The point I want to make is the use of Math.max() to find the highest number from a selection of numbers.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/max
function check_numbers(count, a, b, c) {
if(count === 8) {
var numArray = [a, b, c];
var highest = Math.max.apply(null, numArray);
console.log(highest);
if (highest === a) {
console.log('a is highest');
} else if (highest === b) {
console.log('b is highest');
} else if (highest === c) {
console.log('c is highest');
}
}
}
check_numbers(8, 1 , 2, 5);
check_numbers(8, 5, 2, 1);
check_numbers(8, 1 , 5, 2);
Have you also taken into account that multiple answers could share the highest count?
My 2 cents on that:
var count = count_a = count_b = count_c = 0;
$('.radio-select').on('click', function() {
var chosen_option = $(this).val();
if (chosen_option == 'a') {
count_a++;
}
else if (chosen_option == 'b') {
count_b++;
}
else if (chosen_option == 'c') {
count_c++;
}
if (++count == 8) {
check_numbers(count_a, count_b, count_c);
}
});
function check_numbers(a, b, c) {
var highest = ((a > b && a > c) ? a : (b > c)? b : c),
multiple = false,
alertText = '';
if (a == highest) {
alertText += 'A';
}
if (b == highest) {
if (alertText != '') {
multiple = true;
alertText += ' and ';
}
alertText += 'B';
}
if (c == highest) {
if (alertText != '') {
multiple = true;
alertText += ' and ';
}
alertText += 'C';
}
alert(alertText + ' ' + (multiple ? 'are' : 'is') + ' highest!');
}

javascript for (i = 0; i < XXX.length; i++) -> length question

for (m = 0; m < troopsCount.length; m++) {
//FM_log(7,"i="+i+" m="+m);
//FM_log(7,"tipoTropaPrioritaria[m] = "+tipoTropaPrioritaria[m]);
//FM_log(7,"troopsCount[m] = "+troopsCount[m]);
//FM_log(7,"availableTroops[m] = "+availableTroops[m]);
if ((tipoTropaPrioritaria[m] == null || tipoTropaPrioritaria[m] == "undefined")
|| (troopsCount[m] == null || troopsCount[m] == "undefined") ||
(availableTroops[m] == null || availableTroops[m] == "undefined"))
return "alternaTropas(): ERRO - tipoTropaPrioritaria[m] || troopsCount[m] || availableTroops[m] null ou undefined";
if ((parseInt(tipoTropaPrioritaria[m]) != 0) && (parseInt(troopsCount[m]) != 0)) {
naoServe = true;
break;
}
else {
if ((parseInt(availableTroops[m])) < (parseInt(troopsCount[m]))) {
naoServe = true;
break;
}
else if (m < troopsCount.length) {
naoServe = true;
}
else { //means m >= troopsCount.length
naoServe = false;
}
}
}
my question is: the last statement
else { //means m >= troopsCount.length
naoServe = false;
}
will it ever be evaluated since
for (m = 0; m < troopsCount.length; m++)
???
No, it won't be executed, assuming that m and troopsCount aren't modified in the loop itself (which in this example they don't seem to be).
As I believe you're pointing out, the loop's conditional would prevent the loop from running again if m were greater than or equal to troopsCount.length at the start of the loop.
Nope. It should never happen.
The loop stops immediately once m < troopsCount.length is false. As such, m >= troopsCount.length will never be true inside the loop, unless you change its value inside the loop itself (which you don't, in this sample).
No. The loop is only evaluated as long as m < troopsCount.length. So m will never be >= troopsCount.length as long as you don't modify m or troopsCount.length inside the loop.
let´s assume troopsCount.length = 10
when m = 9 it will execute all the code in the loop right, but when m = 10 it won´t execute anything.
so if I change it this way:
else {
if ((parseInt(availableTroops[m])) < (parseInt(troopsCount[m]))) {
naoServe = true;
break;
}
else if (m < (troopsCount.length - 1)) { // troopsCount.length - 1 = 9, m < 9 = m from 0 to 8
naoServe = true;
}
else { // troopsCount.length = 9
naoServe = false;
}
}
}
it would work, right?

Categories