- #1
DaveC426913
Gold Member
- 22,497
- 6,168
- TL;DR Summary
- How preserve the last value to compare it to the new one without exiting the loop
My brain is misfiring.
I have a start value (integer) that I perform an operation on that will iteratively cause it to converge on some (unknown) integer value.
I stop the iteration when the new value is the same as the old one (i.e. it has stopped changing).
Until that happens, I keep iterating.
To know that it's converged, I set the lastVal equal to thisVal before iterating.
But as soon as I do this, it meets the criteria for exiting the loop.
So I only get one iteration.
This is JavaScript, but it works fine as pseudo-code:
I tried testing it without setting it, but of course that doesn't make the problem go away:
What am I missing?
Maybe a third temp variable?
I guess I could do an infinite loop that breaks manually when the criteria is met...
I have a start value (integer) that I perform an operation on that will iteratively cause it to converge on some (unknown) integer value.
I stop the iteration when the new value is the same as the old one (i.e. it has stopped changing).
Until that happens, I keep iterating.
To know that it's converged, I set the lastVal equal to thisVal before iterating.
But as soon as I do this, it meets the criteria for exiting the loop.
So I only get one iteration.
This is JavaScript, but it works fine as pseudo-code:
Code:
lastVal=-1
thisVal=i;
while (thisVal!=lastVal){
thisVal = doAThingTo(thisVal);
counter++;
lastVal = thisVal; // here's the problem
}
prt(counter);
I tried testing it without setting it, but of course that doesn't make the problem go away:
Code:
lastVal=-1
thisVal=i;
while (thisVal!=lastVal){
if (doAThingTo(thisVal)) != lastVal){
thisVal = doAThingTo(thisVal);
counter++;
lastVal = thisVal; // still a problem
}
else{
//break;
lastVal = thisVal;
}
}
prt(counter);
What am I missing?
Maybe a third temp variable?
I guess I could do an infinite loop that breaks manually when the criteria is met...
Code:
lastVal=-1
thisVal=i;
while (true){
thisVal = doAThingTo(thisVal);
if (thisVal == lastVal) {
break;
}
else {
counter++;
lastVal = thisVal;
}
}
prt(counter);