Number triangle
Given a row count n, return a triangle whose rows count up from 1, as an array of n strings. Row 1 is "1", row 2 is "12", and row i runs 1 to i. The counting restarts on every row, and the numbers are written with no separator between them.
Examples
Example 1
- Input
- n = 5
- Output
1 12 123 1234 12345
Every row begins at 1 again and stops at its own number.["1","12","123","1234","12345"]
Example 2
- Input
- n = 10
- Output
1 12 123 1234 12345 123456 1234567 12345678 123456789 12345678910
Row 10 ends["1","12","123","1234","12345","123456","1234567","12345678","123456789","12345678910"]910, which is 9 followed by 10 — with no separator, a two-digit number runs into its neighbour.
The Code
function numberTriangle(n) {
const rows = [];
for (let row = 1; row <= n; row++) {
let line = "";
for (let col = 1; col <= row; col++) {
line += col;
}
rows.push(line);
}
return rows;
}
numberTriangle(5);The first 19 calls, of 27. This one does not fit on a page.
Explanation
A row prints its own count of positions, not a running total, so it depends on nothing outside itself. That is the whole difference from Floyd’s triangle: the same two loops, printing a different thing.
- 1
rowis 1 and the inner loop runs whilecolis at mostrow.line += colappends the counter itself rather than a star, so the row reads"1".10row=1col=1
rows.push("1")
- 2
rowis 2.colis declared in the inner loop’s own header, so it starts at 1 again here — the row reads"12"rather than carrying on from where row 1 stopped.10121row=2col=1 then 2
rows.push("12")
- 3
rowis 3, socolruns 1, 2, 3. Every number a row prints is worked out fromcolalone, which is why no row depends on any other.101211232row=3col=1 … 3
rows.push("123")
- 4
rowis 4 — four passes, the digits 1 to 4.10121123212343row=4col=1 … 4
rows.push("1234")
- 5
rowis 5, socolruns 1 to 5 and the row reads"12345".row++then failsrow <= nand the five strings are returned.10121123212343123454row=5col=1 … 5
return rows → 5 rows
More like this
All star & number patterns examples (12) →- Star triangle The inner loop runs as far as the row number — that is the whole idea.
- Inverted triangle Same triangle, counted downwards instead of up.
- Star pyramid Leading spaces do the centring; stars go up in odd numbers.
- Star diamond A pyramid, then the same pyramid upside down — minus the shared row.
- Hollow square Fill only the border — every interior cell is a space.
- Butterfly Two wings of stars with a gap between them that closes and reopens.