I want to print this
1 2 3 4 5
2 3 4 5 6
3 4 5 6 7
4 5 6 7 8
5 6 7 8 9
The code appears to look like this, after many guesses
var a=5;
for (var i = 1; i <= a; i++) {
var result="";
for (var j = 1; j <= a; j++) {
result +=(i+j - 1)+ " ";
}
console.log(result);
}
But I still can't quite understand why if the var result declaration is in some other place (for example outside the loops) the result is completely different.
It is not the declaration, which is hoisted for var, but the first value for each row.
var a = 5,
result;
for (var i = 1; i <= a; i++) {
result = "";
for (var j = 1; j <= a; j++) {
result += (i + j - 1) + " ";
}
console.log(result);
}
You can take the declaration of result out of the loop as in:
var a = 5, result;
for (...
...
But you must clear it in each outer loop iteration or it will print an ever increasing row of repeated patterns per iteration.
Final code is:
var a = 5, result;
for (var i = 1; i <= a; i++) {
result = ""; //Clearing happens here.
for (var j = 1; j <= a; j++) {
result += (i + j - 1) + " ";
}
console.log(result);
}
Related
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
This question already has answers here:
Print an output in one line using console.log()
(13 answers)
Closed last year.
Instead of 1 index on each row, I want horizontal not vertical returns.
let n = [6];
function staircase() {
for (let i = 1; i <= n; i++) {
for (let j = 1; j <= n - i; j++) {
console.log("0");
}
for (let k = 1; k <= i; k++) {
console.log('#');
}
}
}
staircase();
But I need it to render like this. (This works using Java; it's the same logic, but renders differently.)
#
##
###
####
#####
######
console.log prints one line each therefore i put 2 variables to keep the empty string and hash string and after the loops logged the concatenation of the strings
let n = 6
function staircase() {
for (let i = 1; i <= n; i++) {
let emptyString = '';
let hashString = '';
for (let j = 1; j <= n - i; j++) {
emptyString += " ";
}
for (let k = 1; k <= i; k++) {
hashString += '#'
}
console.log(emptyString + hashString)
}
}
staircase();
const n = [6]
for (let i = 1; i <= n; i++) {
//
// this array stores the results;
//
const array = [];
//
for (let j = 1; j <= n - i; j++) {
array.push("0");
}
for (let k = 1; k <= i; k++) {
array.push('#');
}
// adding `toString`, does the magic
console.log(array.toString())
}
I need to create java script program who print mirror numbers triangle from N. I tested some ways and get the 50% from task:
let n = 5;
function generatePyramid(num) {
let number = '';
for (let i = 1; i <= num; i += 1) {
console.log(number += i);
}
}
generatePyramid(n);
This code print triangle only from 1 to 5. How to print triangle from 5 to 1?
Also my print need to be with space between 1 2 3 4 5... not 12345.
I have similar code from java with array, but can't transform it to JS: https://pastebin.com/9dqqE8J6
This is the final output:
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
1 2 3 4
1 2 3
1 2
1
One option would be to add a while loop that slices off characters from the number string until it's empty:
let n = 5;
function generatePyramid(num) {
let number = '';
for (let i = 1; i <= num; i += 1) {
console.log(number += i);
}
while (number.length > 1) {
number = number.slice(0, number.length - 1);
console.log(number);
}
}
generatePyramid(n);
To add spaces as well, one option is:
let n = 5;
const log = str => console.log(str.replace(/.(?!$)/g, '$& '))
function generatePyramid(num) {
let number = '';
for (let i = 1; i <= num; i += 1) {
log(number += i);
}
while (number.length > 1) {
number = number.slice(0, number.length - 1);
log(number);
}
}
generatePyramid(n);
<script>
let n = 5;
function generatePyramid(num) {
let number = '';
for (let i = 1; i <= num; i += 1) {
for (let j = 1; j <= i; j += 1)
document.writeln(j+" ");
document.writeln("<br>")
}
for (let i = 4; i >= 1; i -= 1) {
for (let j = 1; j <= i; j += 1)
document.writeln(j+" ");
document.writeln("<br>")
}
}
generatePyramid(n);
</script>
Try This using the same code but i have taken another loop named j
I need to split a number to number of sections
I want number of sections, between each consecutive numbers in each section the number of the sections
For example
If the given number is 20 and the number of sections is 3
then need to split numbers 1 to 20 into three sections.
So the result will be
section 1 = [1,4,7,10,13,16,19] // between any
section 2 = [2,5,8,11,14,17,20]
section 3 = [3,6,9,12,15,18]
I'm using javascript to do this.... any idea
Sorry for my bad English
You could use two nested for loops and count the sections and the value to max.
function getSection(sections, max) {
var value, result = [], i;
for (i = 1; i <= sections; i++) {
result.push([]);
for (value = i; value <= max; value += sections) {
result[i - 1].push(value);
}
}
return result;
}
console.log(getSection(3, 20));
Something like that:
function get_s(s_cnt, w_num) {
var a = new Array(s_cnt), b = Math.ceil(w_num/s_cnt), c = w_num;
for (var i=0; i<s_cnt; i++) {
var b_ = (b < c) ? b : c; c -= b;
a[i] = new Array(b_);
for (var j=0; j<b_; j++) {
a[i][j] = j*s_cnt + i + 1;
}
}
return a;
}
var s = get_s(3,20);
for (var i=0; i<3; i++) console.log("section "+(i+1)+": "+s[i].join(", "));
I am not sure how to phrase this, so please re-title this question if it doesn't make sense. Anyways, this is what I am trying to do.
I have a variable with the length of 9.
And then I have another variable with the length of 3.
How do I write a loop that iterates through all 9 but starts over every third time?
For example: I have this,
x = 3;
l = 9;
for ( var i = 0; i < l; i++)
{
console.log(i + 1);
}
output = 1,2,3,4,5,6,7,8,9
The output I want to create
output = 1,2,3,1,2,3,1,2,3
I was thinking there might be away to do this with an if statement or possibly modulus, but wasn't quite sure how to implement it. What would be a good way to do this? Thanks in advance.
Embrace the modulus:
function expand(length, loop_length) {
for (var i = 0; i < length; i++) {
console.log(i % loop_length + 1);
}
}
expand(9, 3) // => 1, 2, 3, 1, 2, 3, 1, 2, 3
x = 3;
l = 9;
for ( var i = 0; i < l; i++)
{
console.log(i % x + 1);
}
output = 1,2,3,1,2,3,1,2,3
See it in action here: http://jsfiddle.net/BgBGL/
If you want to loop from a min value to a max value a specific number of times, the easiest way is just to have 2 loops, like this:
var min = 1, max = 3, times = 3;
for (var i = 0; i < times; i++) {
for (var j = min; j <= max; j++) {
console.log(j);
}
}
Or if you want to fix total length of the sequence, then yes, you can do it with a single loop and a little bit of math:
var min = 1, max = 3, totalLength = 9;
for (var i = 0; i < totalLength; i++) {
console.log((i % (max - min + 1)) + min);
}
For that case, this works:
x = 3;
l = 9;
for ( var i = 0; i < l; i++)
{
var num=(i %(x+1)) || 1;
console.log(num);
}
You could go mad with following syntax:
var i = 0;
do {
console.log(i++ % 3 + 1);
} while (i < 9);
Alternative, you could define 3 and 9 as a variable also.
I took an advantage of the fact that calling i++ will display old variable and increases it by 1 after, so I saved some bits!
See: fiddle example
x = 3;
l = 9;
for ( var i = 0; i <= l; i++)
{
for ( var j = 1; j <= x; j++)
{
console.log(j);
}
}