Reputation: 16301
What would be the most efficient way to get a triangle-like shape of integers with rows equal to the given integer. Also, the first line should start with just one integer and after every new line, increments one character till it is also equal to integer?
E.g. If I input 5, I want this to return:
5
55
555
5555
55555
Or if I input 3, I will get:
3
33
333
What I have tried so far:
var n = 5;
for (i = 0; i < n; i++) {
var x = (n.toString().repeat(n) + '\n').repeat(n);
}
document.getElementById('output').textContent = x;
#output {
padding: 10px;
background-color: #000;
color: #FFF;
font-size: 16px;
white-space: pre-line;
}
<div id="output"></div>
Upvotes: 0
Views: 36
Reputation: 42304
I would make use of two loops. The inner loop would output the number, looping until it is less than the outer loop plus 1 (to cover the first output). The outer loop would handle line breaks. Both would add to the existing textContent
with +=
.
This can be seen in the following:
var n = 5;
for (i = 0; i < n; i++) {
for (j = 0; j < i + 1; j++) {
document.getElementById('output').textContent += n;
}
document.getElementById('output').textContent += "\n";
}
#output {
padding: 10px;
background-color: #000;
color: #FFF;
font-size: 16px;
white-space: pre-line;
}
<div id="output"></div>
Also note that you're looking for font-size
rather than text-size
.
Upvotes: 1
Reputation: 33399
You need to build the string incrementally and repeat according to the current iteration.
var n = 5;
var x = '';
for (var i = 1; i <= n; i++) {
x += n.toString().repeat(i) + '\n';
}
document.getElementById('output').textContent = x;
#output {
padding: 10px;
background-color: #000;
color: #FFF;
text-size: 16px;
white-space: pre-line;
}
<div id="output"></div>
Upvotes: 2