Floyd’s triangle
Given a row count n, return Floyd’s triangle as an array of n strings: the counting numbers laid out in rows of growing length, row 1 holding one number, row 2 the next two, row n the next n. The numbering runs on across rows and never restarts, and the numbers within a row are separated by a single space.
Examples
Example 1
- Input
- n = 5
- Output
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
Fifteen numbers over five rows, and row 5 begins where row 4 stopped.["1","2 3","4 5 6","7 8 9 10","11 12 13 14 15"]
Example 2
- Input
- n = 3
- Output
1 2 3 4 5 6
Three rows use 1 + 2 + 3 = 6 numbers, so the last one is 6.["1","2 3","4 5 6"]
The Code
function floydsTriangle(n) {
const rows = [];
let counter = 1;
for (let row = 1; row <= n; row++) {
const line = [];
for (let col = 1; col <= row; col++) {
line.push(counter);
counter++;
}
rows.push(line.join(" "));
}
return rows;
}
floydsTriangle(5);The first 19 calls, of 27. This one does not fit on a page.
Explanation
The rows only decide where the line breaks fall; the numbers are one uninterrupted count. What a row opens with is whatever the row before it left off at — the one thing a row cannot work out on its own.
- 1
counteris declared before either loop, so there is one of it for the whole run.rowis 1, the inner loop runs once, and it pushescounterontolinebeforecounter++moves it on.10counter=1row=1
rows.push("1")
- 2
rowis 2.lineis a fresh array — it is declared inside the outer loop — butcounteris not: it comes into this row still holding 2, so the row takes 2 and 3.102 31counter=2row=2
rows.push("2 3")
- 3
rowis 3, andcounterpicks up at 4 because that is where row 2 left it. What a row starts with is not a fact about the row; it is whatever the row before it stopped at.102 314 5 62counter=4row=3
rows.push("4 5 6")
- 4
rowis 4 andcounteris at 7, so the row takes 7, 8, 9 and 10. Declaringcounterinside the outer loop instead would reset it to 1 here and the row would read1 2 3 4.102 314 5 627 8 9 103counter=7row=4
rows.push("7 8 9 10")
- 5
rowis 5 andcounteris at 11, so the last row takes 11 through 15.line.join(" ")puts a single space between them and the five strings are returned.102 314 5 627 8 9 10311 12 13 14 154counter=11row=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.