Please review the code below, note the condition of my for loop depends on the step parameter.
Rather than every time the condition is executed it determines which branch to use, I would like to test that once - I had supposed I could create a delegate or of the condition but it doesn't seem to work.
Is it possible in JS to do this?
Code:
function(start, end, step) {
if (step === undefined) {
step = 1;
}
var result = [];
for (; (step < 0) ? start >= end : start <= end; start += step) {
result.push(start);
}
return result;
}
My attempt:
function(start, end, step) {
if (step === undefined) {
step = 1;
}
var condition = (step < 0) ? start >= end : start <= end;
var result = [];
for (; condition; start += step) {
result.push(start);
}
return result;
}
To do this, you need to make condition a function, like below. But even if you do, the condition is still executed at every iteration of the loop.
var condition = (step < 0) ?
function(start){
return start >= end;
} :
function(start){
return start <= end;
};
var result = [];
for (; condition(start); start += step) {
result.push(start);
}
Related
Doing a basic binary search problem, but how do you know if it actually works if you cant see the number that's being returned??
function binarySearch(arr, val) {
let start = 0;
let end = arr.length - 1;
while (start <= end) {
let mid = Math.floor((start + end) / 2);
if (arr[mid] === val) {
return mid;
}
if (val < arr[mid]) {
end = mid - 1;
} else {
start = mid + 1;
}
}
return -1;
}
let arr = [1,9,3,4,5,7,2];
binarySearch(arr, 9);
If you want to debug or just see the print , you can try debugging option in any of the code editor or just add print before return statements with time , to realize what is returned
The binary search only works if the array is sort.
Use arr.sort()
I'm trying to work through a binary challenge and it requires setting a midway point between the start and end of an array.
This is the code:
function binary (val, nums) {
var start = nums[0];
var end = nums.length -1;
var found = false;
var mid = Math.floor((start + end)/2);
var position = -1;
while(!found && start <= end) {
if (nums[mid] === val) {
found = true;
position = mid;
}
else if (nums[mid] > val) {
end = mid -1;
}
else {
start = mid + 1;
}
}
return position;
}
console.log(binarySearch(12, [1,2,3,4,5,6,7,12]))
The console returns nothing but the function doesn't stop either. However, if I declare var mid outside the loop and then set the value within the loop like so
var mid;
while(!found && start <= end) {
mid = Math.floor((start+end)/2)
if (nums[mid] === val) {
found = true;
position = mid;
}
else if (nums[mid] > val) {
end = mid -1;
}
else {
start = mid + 1;
}
}
It returns the correct value. Why is this?
In the first code snippet (outside while loop), you are never changing mid value where as in second code snippet, you are updating mid in each iteration based on start and end values and hence the difference in result.
I want to check a condition for k times for a value to be true, inside a For loop, each time I want to wait 2 seconds, after that I want to go next iteration of the for a loop. For example, I tried something like below -
var k = 0;
for (let i = 0; i < B.length; i++) {
setTimeout(function F_stTimer() {
if (B[i].innerText === "S") {
var A = "True"; //just for example
if (A === true && k == 0) {
// Do something
k = k + 1;
i = i - 1; // so , I can check the ith element again once start the loop again
} //if
else if (A === true && k > 0 && k < 5) { //checking 5 times for A to be false
k = k + 1;
}, i * 2000);
i = i - 1;
} //if
else if (A === true && k == 5) {
k = 0;
} //if
} // if
}, 5000);
} // i loop
But the above type of code is not working because I do not change when it is inside setTimeout.
Anyway, can anyone help me with the problem I have?
One does not need to follow the way I mentioned above, what I want to do is-
check a condition for k times for a value to be true, inside a For loop, each time I want wait t seconds (duration of each delay/interval of delay), after that, I want to go next iteration of the for a loop.
Plz comment for further clarification.
You could take an interval and check a counter.
var counter = 0,
interval = setInterval(function () {
counter++;
if (counter === 5) {
counter = 0;
console.log('five');
} else {
console.log('not five');
}
}, 1000);
You could write a function that takes two arguments:
howManyTimes - number of times you want to iterate
howOften - in what intervals you want to do the check (in milliseconds)
function checkInIntervals(howManyTimes, howOften) {
var counter = 0;
var interval = setInterval(function() {
counter++;
if (counter === howManyTimes) {
clearInterval(interval);
}
// do something
console.log(counter, 'iteration')
}, howOften)
}
// run the function
checkInIntervals(10, 2000);
Inside the interval the counter is incremented and when it's equal the the desired number of iterations, the interval is cleared and the execution stops.
I saw a question in leetcode.
Also,I found solution in it.
And one thing i don't understand is this line of code
while(n-- >1)
Could someone explain --> meaning?
Here is the JS:
var countAndSay = function(n) {
var result = "1";
var prev;
var count;
var tmp;
while (n-- > 1) {
prev = result[0];
count = 1;
tmp = [];
for (var i = 1; i < result.length; i++) {
if (prev === result[i]) {
count++;
} else {
tmp.push(count, prev);
prev = result[i];
count = 1;
}
}
tmp.push(count, prev);
result = tmp.join("");
}
return result;
};
console.log(countAndSay(4))
One last thing,Could someone explain what is this question's meaning.
I still don't understand why 2 is 11,3 is 21,4 is 1211 and 5 is 111221.
The expression
n-- > 1
means: subtract one from n, and check whether its value before the subtraction was greater than 1.
while (n-- > 1) {
// rest of the code
is equivalent to
while (true) {
if (n > 1) {
n--;
// rest of the code
} else {
// n is decremented regardless:
n--;
// initial condition was not fulfilled:
break;
}
Or, with the negation of the condition:
while (true) {
const origN = n;
n--;
if (!(origN > 1)) {
break;
}
// rest of the code
That means you check whether the n is greater than 1 and after that decrement n by 1.
That means, subtract 1 from n and check if the result is greater than 1.
n-- in any part of the code is equivalent to n = n - 1, or ``n -= 1`, in that loop is a consised way to subtract and evaluate.
The expression (n-- > 1) is similar to comparing the value of n greater than 1. But the thing which you must notice is the value of n will not be decremented(at the beginning) while comparing here. This is because the value of n is first compared with 1 after that only, the value of n is decremented. To understand this clearly, you can take a look over this.
function test(name) {
var n = 5;
while (n-- == 5) { //Here the decrement doesn't takes places so it gets inside the block
console.log(n); //This statement returns the value of n as 4.
}
}
const testing = new test();
I'm looking for the sum of a range but I keep getting "undefined." I believe something's in the wrong spot but I'm not sure as to what it is.
Part 1: "Write a range function that takes two arguments, start and end, and returns an array containing all of the numbers from start up to (and including) end:
Part 2: "Next, write a sum function that takes an array of numbers and returns the sum of these numbers. Run the previous program and see whether it does indeed return 55."
// Part 1
function deRange(start, end, step) {
if (step === null) {
step = 1;
var blank = [];
if (step > 0) {
for (var i = start; i <= end; i += step)
blank.push(i);
} else {
for (var i = start; i >= end; i += step)
blank.push(i);
}
}
return blank;
}
// Part 2
function theSum(blank) {
var total = 0;
for (var i = 0; i < blank.length; i++)
total += blank[i];
return total;
}
console.log(deRange(1, 10));
console.log(deRange(5, 2, -1));
console.log(theSum(deRange(1, 10)));
You have misplaced your curly brackets. This works:
function range(start, end, step) {
if (step === null) {
step = 1;
}
var blank = [];
if (step > 0) {
for (var i = start; i <= end; i += step)
blank.push(i);
} else {
for (var i = start; i >= end; i += step)
blank.push(i);
}
return blank;
}
console.log(range(1, 5, null));
Note that you are checking if step is null, so the user still needs to explicitly give null as argument. If you want to set a default value if no third argument is provided, use e.g.:
step = step || 1;
(This also treats 0 as a missing argument, which is good.)
Below I fixed your code and commented some errors you have in it. Check the demo.
// Part 1
function deRange(start, end, step) {
/**
* If you want to make sure 'step' is not 0 (zero) either,
* change the if like this:
* if(!step) { step = 1; }
*/
if (step === null || typeof step === 'undefined') { // <- also check when 'step' was not passed as argument
step = 1;
} // <-- curly brace here!
var blank = [];
if (step > 0) {
for (var i = start; i <= end; i += step)
blank.push(i);
} else {
for (var i = start; i >= end; i += step)
blank.push(i);
}
return blank;
}
// Part 2
function theSum(blank) {
var total = 0;
for (var i = 0; i < blank.length; i++)
total += blank[i];
return total;
}
console.log(deRange(1, 10));
console.log(deRange(5, 2, -1));
console.log(theSum(deRange(1, 10)));