I have a while loop that works when I use a condition such as while(x > 0) however when I change it to while(x == true) or while(x) it turns into an infinite loop despite me having a condition that changes the variable to false.
Here's how that part of my code is set up.
let appendNums = ['8','2','8','14'], //for testing purposes
carryCheck = true,
incAmount = 0;
incAmount = appendNums.length - 1;
while(carryCheck){
let currentNum = appendNums[incAmount];
if(currentNum.length > 1){
let numSplitter = currentNum.split(''),
equation = Number(appendNums[incAmount - 1]) + Number(numSplitter[0]);
appendNums[incAmount] = numSplitter[1];
appendNums[incAmount - 1] = equation.toString();
incAmount = incAmount - 1;
}
else{ carryCheck = false; break; }
}
Overall what's happening, is I'm working on a function to do addition the way we've been taught to do it on paper in school with "carrying the one over". I'm trying to tell the while loop to stop running when the .length of the current number is less than 2, indicating it's a single digit number and nothing else needs to be carried. In this instance the while(x > 0) way of doing it wouldn't work because it keeps running beyond where I want it to stop.
I double checked the syntax on MDN and have come across a few posts on here where people made the mistake of doing x = true instead of x == true or x === true. Can anyone spot what I'm doing wrong here?
UPDATE
I just tried changing the while loop to while(appendNums[incAmount] > 1) and it still goes into an infinite loop.
Number(appendNums[incAmount - 1]) + Number(numSplitter[0]) will return NaN at some point because you do not check the array bounds.
By using equation.toString() and inserting it into appendNums[incAmount -1], currentNum will always be the string "NaN" in the next iteration.
Since the string "NaN" has a length of 3, currentNum.length > 1 will always be true.
Related
let number = 0;
while (true) {
if (number%2 === 0) continue;
console.log(number);
number ++;
}
I wanted to infinite loop to print out only odd numbers. But this doesn't seem to work. What am I doing wrong?
Let's have a brief understanding of the code execution.
When the following code is executed...:
let number = 0;
while (true) {
if (number%2 === 0) continue;
console.log(number);
number ++;
}
...the following happens:
The first line allocates memory for a variable named number and stores a value of 0.
The while loop starts, and it checks whether the condition is true, and yes it is, and always will be, as the condition is simply true.
Then, it checks whether the number mod 2 returns 0, and definitely, it does, since 0รท2 is 0 and the remainder is 0, so the condition inside the if statement is true, and therefore it executes the code correspondingly. When it sees continue, it jumps back to step 2 and checks the while loop condition, then comes back here, then goes back to step 2, then again comes back here and this never ends(ends when you stop the code execution or close your browser obviously).
Simply put, it never goes forward to the console.log and the number++ line. This is why your code isn't working.
The code from others work because the control actually moves forward in the code and never actually becomes stuck in the above loop.
Try this code
let number = 0;
while (true) {
if (number % 2 != 0)
console.log(number);
number ++;
}
The code you're using will not work because you defined number=0 and then you're checking the condition if(number%2==0) continue; so this condition will always return true because the number is defined 0 and the number++ will never increase.
let number = 0;
while (true){
if (++number % 2 == 1){
console.log(number);
}
}
no need a continue statement, just check the remainder is 1 the print the value in the loop.
you can further shorten the if condition as if (++number % 2)
You should increment the number when it is even also, to check the next number and so on:
let number = 0;
while (true) {
if (number%2 === 0){
number++;
continue;
}
console.log(number);
number ++;
}
Whatever number is, increment it first. Otherwise, when it is even, it never reaches to number++ any more.
let number = 0;
while (true) {
number ++;
if (number%2 === 0) continue;
console.log(number);
}
I have an easy drill to print all the even numbers between 1-1000.
I want to set the condition in the line of the loop and not below it..
This is what I've tried:
for (let i = 1; i <= 1000 && i % 2 == 0 ; i++) {
document.write(i + " ");
// I dont want the condition here !!!
}
I searched the forum and tried this too:
for (let i = 1;( (i <= 1000) && (i % 2 == 0) ); i++) {
document.write(i + " ");
}
It looks like the same code I think, but there is nothing in the console when I run the code..
The test condition in the loop header determines whether the loop will continue to iterate. Because the first value of i is 1, and 1 is not even, the loop body is never run.
The whole test expression must be true (well, "truthy") for the loop not to stop. Therefore, you cannot place the evenness test in the loop header. It must be a separate test inside the loop body.
Now, you could do this without a test by starting the iteration at 2 instead of 1 and adding 2 on each iteration. Then you don't need to test for evenness at all:
for (let i = 2; i <= 1000; i += 2)
document.write(i);
I have an array of sorted numbers, and a starting value. For the sake of simplicity, let's say the array has values from 1 to 20, and the starting value is 10.
The value to find can change every 5 seconds, based on user input. It can either increase or decrease and it always keeps in the range of values of the table.
The only thing I cannot know is whether the value is increasing or decreasing. I have come up with the (very) simple algorithm below.
Can you think of a way to improve it ?
Ideally, I think the best approach would be to run the two for loops simultaneously and return when value is found... Using workers for example ?
In my example, the "going down" for loops is exhausted before "going up" starts running. Which, idealy, shouldn't happen, since I'm trying to spread tries -1/+1 each time.
Btw : the reason why I'm trying to do this is because I have to run quite heavy functions in the for loops. The code is running in node.js context.
Here's a JSFiddle and the code below
const attempts = document.getElementById('attempts');
let attemptsCount = Number(attempts.textContent);
const lastValue = 10;
const valueToFind = 16; //this must be found in the least possible number of attempts
const table = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20];
const lookup = () => {
for (var i = lastValue; i > 0; i--) {
if (table[i] == valueToFind) {
alert('Found going down');
return;
} else {
attemptsCount++;
attempts.textContent = attemptsCount;
}
}
for (var i = lastValue; i < table[table.length-1]; i++) {
if (table[i] == valueToFind) {
alert('Found going up');
return;
} else {
attemptsCount++;
attempts.textContent = attemptsCount;
}
}
}
//find new value
lookup();
Right now, each for loop you have runs async from one another...so one side will always finish before the other side starts...which is not ideal.
Remember that for loops are set up to initialize, check if bool statement = true, and set next step...so like if statements, you can implement multiple statements in each scenario.
Reducing the loop attempts can be simple as doing it at the same time:
const lookup = () => {
for (var up = lastValue, down = lastValue-1; up < table[table.length-1] || down > 0; up++, down--) {
if (up < table[table.length-1] && table[up] == valueToFind) {
alert('Found going up');
return;
} else if (down > 0 && table[down] == valueToFind) {
alert('Found going down');
return;
} else {
attemptsCount++;
attempts.textContent = attemptsCount;
}
}
Your JSFiddle updated
Recently began studying Javascript, trying to read out of Javascript: The Definitive Guide and Eloquent Javascript, while going off on my own to experiment with things in order to really etch them in my memory. I thought a good way to get my head around arithmetic operations and conditional statements, I'd build a series of little games based around each Math operator, and began with addition.
function beginAdditionChallenge() {
var x = Math.ceiling(Math.random()*100);
alert(x);
for (var i = 0; i < 3; i++) {
var a = Number(prompt("Provide the first addend.", ""));
var b = Number(prompt("Provide the second addend.", ""));
if (a + b === x) {
alert("Well done!");
break;
}
else if (a + b !== x && i < 3) {
alert("Please try again.");
}
else {
alert("Fail.");
}
}
}
function initChallenge() {
var button = document.getElementById("challengeButton");
button.addEventListener("click", beginAdditionChallenge);
}
window.addEventListener("load", initChallenge);
You can see the whole thing thus far on JSFiddle, here. The idea is that clicking the button generates a random number between 1 and 100, displays it to the user, then prompts them to provide two addends, giving them 3 attempts. If the sum of these addends is equal to the RNG number, it congratulates the user and ends the program. If they do not provide suitable addends, the loop prompts them to try again, until they've hit 3 attempts, at which point the program snarks at them and ends.
I know the event listener is not the failure point here, as when I change beginAdditionChallenge to simply display a test alert, it works, but I don't know what exactly is wrong with the loop I've created.
You did it correctly. However, Math.ceiling isn't a function and should be Math.ceil. In addition, your code (in jsfiddle) should be set to wrap in head. Why? Because right now you call initChallenge when the page loads. However, in your jsfiddle example, the code runs onLoad so the load event never gets called. Essentially, you're adding a load event after the page has loaded.
http://jsfiddle.net/rNn32/
Edit: In addition, you have a for loop that goes up to three. Therefore
else if (a + b !== x && i < 3) {
alert("Please try again.");
}
should be
else if (a + b !== x && i < 2) {
alert("Please try again.");
}
because when i === 2, the user's last chance has ended.
Everything is fine. Just change:-
var x = Math.ceiling(Math.random()*100);
to:-
var x = Math.ceil(Math.random()*100);
The problem is the - operator does not working (in 8th line). See my code below:
array = [0,0,0,0,3,0,0,0,0],
n = 0;
for(var i = 0; i < array.length; i++){
if(n < 9){ //the "n" variable there's only for don't crash the browser with a infinite loop
if(array[i] == 3){
array[i] = 0;
array[i - 1] = 3; //I believe that here is the problem
}
}
n++;
}
console.log(array);
So... I want to move the "3" value to the beginning of the array. But it only work if I use the + operator(in 8th line). Consequently, if I use the + one, the "3" value goes to the end of the array.
Anyone know why the - operator does not working in this case and the + works?
If you change line 8 to:
array[i+1] = 3;
then the number 3 will go all the way to the end of the array (well, beyond the end of the array and I'll be damned to find out what Javascript does then!). This is because the loop traverses the array in increasing order and the position i+1 will be checked right next.
On the other hand, with your current line 8, number 3 goes one position backwards (which has already been checked), so it doesn't go all the way to the beginning of the array, just one position. If you want it to go to all the way in the same fashion, you should reverse the loop (make it traverse the array in descending order of the position i).
What do you think happens when i is 0 and you do - 1?
In your first iteration of the loop, when i is zero, (i - 1) is -1, so you're trying to access array[-1], which is invalid.
Okay, instead of answering "Anyone know why the - operator does not working in this case and the + works?", I will answer what I think is the real question, as stated in the original post: I want to move the "3" value to the beginning of the array. I think this does what is desired:
var array = [0,0,0,0,3,0,0,0,0];
var first_val = 3;
var index = array.indexOf(first_val);
if (index > 0) {
array.splice(index, 1);
array.unshift(first_val);
}
console.log(array);
Inspired by this.
I want to move the "3" value to the beginning of the array
Use the correct answer provided in here. Then use .indexOf() to move it.
Array.prototype.move = function (old_index, new_index) {
if (new_index >= this.length) {
var k = new_index - this.length;
while ((k--) + 1) {
this.push(undefined);
}
}
this.splice(new_index, 0, this.splice(old_index, 1)[0]);
return this; // for testing purposes
};
var array = [0,0,0,0,3,0,0,0,0];
var result = array.move(array.indexOf(3),0);
console.log(result);
JSFiddle Demo