Alphabet triangle
Given a row count n, return a triangle whose rows spell "A", "AB", "ABC" and so on, as an array of n strings. Row i holds the first i letters of the alphabet in capitals, starting from A, and n is no larger than 26.
Examples
Example 1
- Input
- n = 5
- Output
A AB ABC ABCD ABCDE
Five rows, and the last of them spells the first five letters.["A","AB","ABC","ABCD","ABCDE"]
Example 2
- Input
- n = 1
- Output
A
One row, holding the letter the counting starts from.["A"]
The Code
function alphabetTriangle(n) {
const rows = [];
const A = 65;
for (let row = 1; row <= n; row++) {
let line = "";
for (let col = 0; col < row; col++) {
line += String.fromCharCode(A + col);
}
rows.push(line);
}
return rows;
}
alphabetTriangle(5);The first 19 calls, of 27. This one does not fit on a page.
Explanation
Letters sit in a fixed order, so the ith letter is a fixed distance from A. Counting and spelling are then the same job: a row that counts to i spells i letters without being told which ones.
- 1
Ais set to 65, the code for the letter"A".rowis 1, and the inner loop countscolfrom 0 while it is belowrow, so it runs once:String.fromCharCode(A + 0)gives back"A".A0A=65row=1
rows.push("A")
- 2
rowis 2, socoltakes 0 and then 1 and the codes are 65 and 66. Becausecolstarts at 0 rather than 1, the offset added toAis already the distance from the first letter — no adjustment is needed.A0AB1row=2A + col=65, 66
rows.push("AB")
- 3
rowis 3: codes 65, 66 and 67. Each row spells its letters out again from the start rather than adding one to the row above, so nothing is carried between rows.A0AB1ABC2row=3A + col=65 … 67
rows.push("ABC")
- 4
rowis 4 — codes 65 to 68, which is"ABCD".A0AB1ABC2ABCD3row=4A + col=65 … 68
rows.push("ABCD")
- 5
rowis 5 and the codes run 65 to 69, spelling"ABCDE".row++then failsrow <= nand the five strings are returned.A0AB1ABC2ABCD3ABCDE4row=5A + col=65 … 69
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.