Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I try to understand nested for loops in javascript but it's very confusing.
I have this code and I can't understand how it works:
let n = 5;
for (let i = 0; i < n; i++) {
for (let j = 0; j < i; j++) {
console.log(j);
}}
In console I have : 0
1
0
1
2
0
1
2
3
And I'm trying to figure out which loop represent each number.
Run this code:
let n = 5;
let str = '';
for (let i = 0; i < n; i++) {
for (let j = 0; j < i; j++)
str += j;
console.log("Outer: "+i+" Inner: "+str);
str = '';
}
Output is:
Outer: 0 Inner:
Outer: 1 Inner: 0
Outer: 2 Inner: 01
Outer: 3 Inner: 012
Outer: 4 Inner: 0123
As you can see, in the output above, inner loop (the one with variable j) doesn't run, because if you replace the variables with numbers it would be
0 < 0 (i < 0), which isn't true.
The best way for you to understand how nested loops work is to write each step and variable values on the paper, like so:
n = 5
STEP 1:
i = 0
i < n (0 < 5) TRUE
j = 0
j < i (0 < 0) FALSE inner loop doesn't execute
OUTPUT: "Outer: 0 Inner:"
str = ''
STEP 2:
i = 1
i < n (1 < 5) TRUE
j = 0
j < i (0 < 1) TRUE
str = 0
j = 1 (j++)
j < i (1 < 1) FALSE
OUTPUT: "Outer: 1 Inner: 0"
str = ''
And so on... Keep repeating this until the argument in the outer loop is false (i < n).
You must remember, in for loop the sequence of orders executed:
for(let i = 0; i < 5; i++) {
console.log('It works');
}
let i = 0; (this executes only once)
i < 5 (if true run 3 and 4)
run the code in loop
i ++
i < 5 (if true run 6 and 7)
run the code in loop
i++
etc.
Related
Using Construct 3 to build a game.
I want to change this function in the code below (which just randomly assigns a frame count in an array) to something that isn't random, but instead loops in order from indexes 0 to 10 and then back to 0 and then to 10 in order again and loop like that continuously.
random(1,Self.AnimationFrameCount)
Is there a random() equivalent for non-random?
// generator function - yields multiple times, maybe forever
function* oneToTenAndBack(N: number): Generator<number> {
while(true) {
for (let i = 0; i < N; i++) yield i;
for (let j = N; j > 0; j--) yield j;
}
}
let k = 0;
for (let num of oneToTenAndBack(4)) {
console.log(num) // 0 1 2 3 4 3 2 1 0 1 2
if (++k>10) break;
}
let gen = oneToTenAndBack(3);
for (let k = 0; k < 10; k++)
console.log(gen.next()) // {value: number, done: false}
Playground Link
I have gone through this Question and Answer While loop inside while loop JavaScript
function getMaxLessThanK(n, k) {
let i = 1;
while (i < n) {
let j = i + 1;
while (j < n + 1) {
console.log(i, j)
j++
}
i++
}
}
when n = 5, what am I getting is
1 2
1 3
1 4
1 5
2 3
2 4
2 5
3 4
3 5
4 5
undefined
How to avoid this the last line undefined. what is the reason for it?
Can anyone help on this please?
Edit:
This is what the actual thing I am doing below.
If you're running it in a console and get an undefined like this:
This undefined indicates that your statement runs without returning a value. It's not a result of your console.log.
If you make the function return something:
function getMaxLessThanK(n, k) {
let i = 1;
while (i < n) {
let j = i + 1;
while (j < n + 1) {
console.log(i, j)
j++
}
i++
}
return 'return value';
}
Then you'll get
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 1 year ago.
Improve this question
I am trying to make a Javascript pattern that accepts a user input in the form of a digit and returns the below output:
******1
****1 2 1
***1 2 2 1
**1 2 3 2 1
*1 2 3 3 2 1
1 2 3 4 3 2 1
*1 2 3 3 2 1
**1 2 3 2 1
***1 2 2 1
****1 2 1
*****1
However I am stuck at the a pattern that looks like this:
1
1 2 1
1 2 3 2 1
1 2 3 4 3 2 1
1 2 3 2 1
1 2 1
1
This is the code I wrote until now.
function selectNo() {
var selectedNo = document.getElementById("select-number").value;
for (var i = 1; i <= selectedNo; i++) {
for (var l = 0; l < (selectedNo - i); l++)
document.write(" ")
for (var j = 1; j <= i; j++)
document.write(" " + j)
for (var k = i - 1; k >= 1; k--)
document.write(" " + k)
document.write("<br>");
}
for (var i = 1; i <= selectedNo; i++) {
for (var l = 0; l < i; l++)
document.write(" ")
for (var j = 1; j <= (selectedNo - i); j++)
document.write(" " + j)
for (var k = selectedNo - i - 1; k >= 1; k--)
document.write(" " + k)
document.write("<br>");
}
}
<input type="number" id="select-number" placeholder="Select your number">
<button onclick="selectNo()">Print the pattern</button>
Any suggestions on how to reach the target pattern? Thank you!
Create a function that returns the array of the next numbers and then you can loop from 1 to the input number.
Then you just need to join the arrays.
function line(len) {
const middle = (len - 1) / 2;
const a = [];
for(let i = 0; i < len; i++) {
if(i < middle) {
a.push(i + 1);
}
else {
a.push(len - i);
}
}
return a;
}
function diamond(len) {
l = len * 2 - 1;
const d = [];
for(let i = 0; i < l; i++) {
const a = line(i + 1).map(v => `${v} `);
const b = new Array(l - a.length).fill(' ').concat(a).join('');
d.push(b);
}
for(let i = l - 2; i >= 0; i--) {
const a = line(i + 1).map(v => `${v} `);
const b = new Array(l - a.length).fill(' ').concat(a).join('');
d.push(b);
}
return d.join('<br/>');
}
function main() {
document.getElementById("result").innerHTML = diamond(document.getElementById("val").value);
}
<input id="val" type="number" placeholder="Select your number">
<button onclick="main()">Print the Pattern</button>
<div id="result" style="font-family: monospace;"></div>
I have the following loop:
for (let i=0; i<7; i+=2) {
for (let j=i; j<i+2; j++) {
console.log(j);
}
console.log('\n');
}
If I execute it I get:
0
1
2
3
4
5
6
7
But it only works on even conditions (0-7 = 8), if I instead put i<8, I get the same:
0
1
2
3
4
5
6
7
Which is bad, it must has returned 8 at the end, but instead doesn't print it. I expect my result when the condition is not even like this:
0
1
2
3
4
5
6
7
8
How can I achieve it? Thanks for your help.
You could use a single loop and add for each odd value a line feed after printing the value.
for (let i = 0; i <= 8; i++) {
console.log(i);
if (i % 2) {
console.log('\n');
}
}
Although Nina's answer is better, for completeness, I post a corrected version of the code that you started with:
let n = 8;
for (let i=0; i<=n; i+=2) {
for (let j=i; j<i+2 && j <= n; j++) {
console.log(j);
}
console.log('\n');
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
so this is what I've achieved so far
function arrayMode(sequence) {
var arr= [];
var mostFreq = 1;
for(var i = 1; i <= 10; i++)
arr[i] = 0;
for(var i = 0 ; i < sequence.length; i++)
arr[sequence[i]]++;
for(var i = 1; i < 10; i++){
if( arr[i] > arr[mostFreq])
mostFreq = i;
}
return mostFreq;
}
so the scope for my case are
The sequence value is >= 1 and <=10
The sequence length is > 0
The sequence is an array of integer
Example 1
Input : sequence = [1, 10, 10]
Output : 10
Example 2
Input : sequence = [1, 3, 3, 3, 1]
Output : 3
It seems easy, I've tried to figure out but I cant find where is the mistake in my code, It's seems legit for me
As suggested by Maxim Krizhanovsky, the last loop should go from 1 to 10 instead of to sequence.length. Here is the working code
function arrayMode(sequence) {
var arr= [];
var mostFreq = 1;
for(var i = 0; i <= 10; i++)
arr.push(0);
for(var i = 0 ; i < sequence.length; i++)
arr[sequence[i]]++;
for(var i = 1; i <= 10; i++){
if( arr[i] > arr[mostFreq])
mostFreq = i;
}
return mostFreq;
}
The output is 10 and 3 respectively to your input.