The following code outer layer for loop is only executed once, wonderfully, why?
let x = -5;
let y = -5;
for (; x < 5; ++x) {
for (; y < 5; ++y) {
console.log(x);
}
}
Because once all inner iterations have finished on the first outer iteration, y is 5, so on the next outer iteration, the condition for the inner iteration (y < 5) is false - the inner loop body never runs again.
No! Outer loop gets executed till x reaches 4 i.e. <5.
you are not resetting value of y before going to inner loop so condition of y is not satisfied and hence its not getting executed.
try putting console.log() before inner loop, then you will get idea of iterations happening.
Related
So, I have an array and I wanted to check if some values are the same or 0. And if not, than it should call the function "end" and stop, but instead it never stops and keeps calling the function "end".
function test() {
loop:
for (var x = 0; x < arr.length; x++) {
if (arr[x] === 0) break;
else if (x + 1 === arr.length) {
for (var x = 0; x < 4; x++) {
for (var y = 0; y < 3; y++) {
if (arr[4 + x + y * 4] === arr[x + y * 4]) break loop;
if (arr[11 - x - y * 4] === arr[15 - x - y * 4]) break loop;
}
}
for (var y = 0; y < 4; y++) {
for (var x = 0; x < 3; x++) {
if (arr[1 + x + y * 4] === arr[x + y * 4]) break loop;
if (arr[14 - x - y * 4] === arr[15 - x - y * 4]) break loop;
}
}
end();
}
}
}
Edit: found the problem, I used the x variable twice.
Sorry for wasting your time
for starters: declare loop iteration variables with let instead of var - variables declared with var are scoped to the function (while let/const are scoped to the code block/loop)
See the following code, to see how let/var result in different outputs
for (var x = 0; x < 3; x++) {
console.log("outer loop var" + x)
for (var x = 0; x < 2; x++) {
console.log("inner loop var" + x)
}
}
for (let x = 0; x < 3; x++) {
console.log("outer loop let" + x)
for (let x = 0; x < 2; x++) {
console.log("inner loop let" + x)
}
}
in the loops with var both loops use the same variable - so the loop is exited after only 1 iteration of the outer loop (+ 2 of the inner one) (since x reaches 3 because both the inner and outer loop use the same variable to iterate - and therefor also add to the same variable after each iteration - so the inner loop is exited, because x reaches 2, then the first iteration of the outer loop ends and 1 is added, which means x becomes 3 and the loop is exited)
int the loops with let both loops each use their own variable, so we get our intended 3 iterations of the outer loop and 3 * 2 for our inner loop.
Could you show matriz data? And explain better what is the requeriment of your problem? Maybe we could find alternatives or apply other logic.
So I solved the twoSum problem which you can find here: twoSum and I know there are better and more efficient solutions but for this one, I am just trying to understand why I get an empty array unless I reassign variable j inside the while loop. See code below. When I tried solving it by assigning j outside of the loop it doesn't work. See code comments.
My halfway answer/initial thought was that by assigning j's value outside of the loop its doing a direct assignment by value which means its value doesn't change since the interpreter only runs top to bottom and doesn't actually go back to check. So this would mean that if j were to be assigned by reference this problem would not occur?? I don't know if I'm on the right track
var twoSum = function (nums, target) {
let indecesArr = [];
let i = 0;
//j declaration without assignment
let j;
//let j = i + 1; //this will cause return to be empty array
while (i < nums.length) {\
//j's value has to be reassigned here otherwise return is an empty [] array
j = i + 1;
while (j < nums.length) {
if (nums[i] + nums[j] === target) {
indecesArr.push(i, j);
}
j++;
}
i++;
}
return indecesArr;
};
console.log(twoSum([3, 2, 4], 6)); //output [1,2]
You are incrementing the value of j in the inner while loop.
So when i =0 meaning nums[i] = 3 then j increments till the very end as their is no matching pair.
So next time when i = 1 & so on j has already traversed till the end of the array. Code inside the second loop never executes from i=1,hence no matching pair
I have a question about how nested loops work in JavaScript.
Imagine I have while() loop ... and inside of that is a for() loop. Each has its own separate ending conditions (see below for a schematic).
My question is this: will the while() loop stop the INSTANT its ending condition is met--even if the for() loop within it is not yet finished? Here is an example.
var i = 0;
while (i < somenumber){
for(var j=0; j < othernumber; j++){
somecode();
i++:
}
}
The code seems to be working, but I want to make sure I understand how these structures are supposed to work. The goal is to get the while loop (and thus also the for loop within) to stop the instant that 'i' has reached 'somenumber', even if j has not yet reached 'othernumber'.
You can use labels and the break command to exit a parent loop directly:
var x = 0, y=0;
b1: {
while (x++ < 5){
b2: {
for(y=0; y < 3; y++){
if (y === 1){
x = 2;
break b1;
}
}
}
}
}
console.log(`x=${x} y=${y}`)
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/break
I suggest you test the code and see what it does. Here I tested with arbitrary numbers and it seems to show that the while loop does not terminate the instant the condition is met. It lets the job finish. Here's an explanation:
Initially, the condition is true, so it goes into the while loop. Once in the while loop, it doesn't check if the condition is true until the next iteration, meaning it won't stop executing the for loop even if the condition is false. Here's the test code:
var i = 0;
while (i < 5){
for(var j=0; j < 10; j++){
console.log(j + ", iter= " + i);
i++;
}
}
This yields:
0, iter= 0
1, iter= 1
2, iter= 2
3, iter= 3
4, iter= 4
5, iter= 5
6, iter= 6
7, iter= 7
8, iter= 8
9, iter= 9
From the output above, we see the for loop doesn't end. It keeps on going because, although the while loop's condition is false, it doesn't check if it's true until the next iteration, allowing the for loop to finish.
I tested it for you:
var i = 0;
while (i < 10){
for(var j=0; j < 12; j++){
somecode(j);
i++;
}
console.log('i',i);
}
function somecode(j) {
console.log('in the for loop', j);
}
The entire for loop is executed, and then the final console.log in the while loop is evaluated.
Each loop will check the condition at the end of the current iteration (when the loop reaches the closing bracket). The only way to stop the while loop inside the for loop is to make something like this:
for(var j=0; j < othernumber; j++){
somecode();
i++;
if (!(i < somenumber)) break; //it exits the for loop
}
When you exit the for loop and reach the closing bracket of the while loop, it will check the while condition and exit from the loop
The following code (looping from 10 to 1) doesn't run in javascript and I can't figure out why. Any advice?
for (var x = 10; x >= 1; x--){
console.log(x);
}
The test in a loop says when to keep looping, not when to stop. When your loop starts, x = 10, so x == 1 is false, and the loop stops immediately.
It should be:
for (var x = 10; x >= 1; x--)
you are setting x = 10, then looping while x == 1, which it isn't so you never loop. You should use "x > 0". The test in the loop is "loop as long as this condition is true".
you are using for loop . for for loop syntax is :
for (statement 1; statement 2; statement 3) {
code block to be executed
}
Statement 1 is executed before the loop (the code block) starts.
Statement 2 defines the condition for running the loop (the code block).
Statement 3 is executed each time after the loop (the code block) has been executed.
so according to yours code :
for (var x = 10; x == 1; x--){
console.log(x);
}
it will first assign x to 10 then it will check condition which is x==1 it will return false and loop will stop. so current version will be:
for (var x = 10; x >= 1; x--){
console.log(x);
}
That's not working because the syntax is not correct. It should be:
for (var x = 10; x >= 1; x--){
console.log(x);
}
The x==1 expression is the stopping condition of the loop and, when it's false, loop stops.
After experimenting with the use of "i++" and "++i" I could not find a difference between their results when used in a 'for' loop.
For example:
for (var i = 0; i < 10; ++i) {
console.log(i);
}
would yield:
0
1
2
3
4
5
6
7
8
9
Shouldn't it be printing out the numbers from 1 to 10, as the iterator is being incremented before console.log(i) executes?
The "increment step" is executed after the loop body is executed. Given
for (a;b;c) {
d
}
the execution order is
a // initialize
b // condition - first iteration
d // loop body
c // "increment"
b // condition - second iteration
d // loop body
c // "increment"
...
b // condition - last iteration - break
So in your case:
var i = 0;
i < 10;
console.log(i); // 0
++i;
i < 10;
console.log(i); // 1
++i;
// ...
i < 10;
The difference between i++ and ++i is only relevant if you do something with the return value, which you don't.
Because the last clause of the for loop only happens at the end of the loop, as its own statement, the behavior of your loop is not affected by this difference. However, imagine you did something like this:
for (var i = 0; i < 10;) {
console.log(++i);
}
for (var j = 0; j < 10;) {
console.log(j++);
}
Then you'd see a difference. The first example would produce numbers 1-10, whereas the second would produce numbers 0-9. That's because f(j++) is equivalent to j += 1; f(j);, whereas f(++i) is more like f(i); i += 1;.
May I advise that while your testing is fine on whatever platform you are using, the standard construct is i++
Always code the standard and isolate various platforms and make exceptions as needed !!!
i++ Simply means increment 'i' by one.
I can speculate ++i means to add 'i' to itself eg if 'i' was 2 then it would then increment to 2,4,8,16,32
But I have never seen ++i used in many places.