How do I match values when I use a different iterating step count other than 1?
Please see the example below. I am interating by 5 since 5 is the speed.
But, how do I stop once I come close to 53. How do I detect and stop start from going way past 53 and make it 53?
var start=0;
var value_to_reach=53;
var increment_speed=5;
while(true) {
if(start>value_to_reach)
{
start-=increment_speed
} else { start+=increment_speed }
if (start==value_to_reach) {
console.log("reached :" + value_to_reach); //Obviously this will never happen with the increment being +5."
}
if (start>54)
{
console.log("Let's break this loop for the sake of stopping this infinite loop. But we couldn't achieve what we want. Not reached " + value_to_reach);
break;
}
}
How to detect if it's close to 53 or not
You can get total steps by this:
var totalRepeation = Math.ceil(value_to_reach / increment_speed);
And so you can create counter that increment one by one and check to see last step.
You can try this one:
var start = 0;
var value_to_reach = 53;
var increment_speed = 5;
let totalRepeation = Math.ceil(value_to_reach / increment_speed);
let i = 0;
while (true) {
if (start > value_to_reach) {
start -= increment_speed
} else { start += increment_speed; i++ }
if (i + 1 >= totalRepeation) {
console.log("you are close to 53. the start numbre is: ", start)
break;
}
if (start == value_to_reach) {
console.log("reached :" + value_to_reach); //Obviously this will never happen with the increment being +5."
}
if (start > 54) {
console.log("Let's break this loop for the sake of stopping this infinite loop. But we couldn't achieve what we want. Not reached " + value_to_reach);
break;
}
}