Star diamond
Given a half-height n, return a diamond of stars as an array of 2n − 1 strings. The first n rows widen from a single * to 2n − 1 stars, each centred behind its own padding, and the rows after them narrow back to a single star. The widest row belongs to both halves and appears exactly once.
Examples
Example 1
- Input
- n = 4
- Output
* *** ***** ******* ***** *** *
Four rows up to seven stars and three back down — seven rows, not eight.[" *"," ***"," *****","*******"," *****"," ***"," *"]
Example 2
- Input
- n = 2
- Output
* *** *
Three rows, and the shared three-star row is written once.[" *","***"," *"]
The Code
function diamond(n) {
const rows = [];
function addRow(stars, spaces) {
let line = "";
for (let i = 0; i < spaces; i++) line += " ";
for (let i = 0; i < stars; i++) line += "*";
rows.push(line);
}
for (let row = 1; row <= n; row++) {
addRow(row * 2 - 1, n - row);
}
for (let row = n - 1; row >= 1; row--) {
addRow(row * 2 - 1, n - row);
}
return rows;
}
diamond(4);The first 22 calls, of 67. This one does not fit on a page.
Explanation
A diamond is a pyramid and its reflection. The two share their widest row, so it is written once and the diamond comes to 2n − 1 rows rather than 2n. Each space is drawn as · in the rows below.
- 1
rowis 1 in the first loop, andaddRow(row * 2 - 1, n - row)is handed 1 star and 3 spaces. The helper lays the spaces down first, then the stars, and pushes the line ontorows.···*0stars=1spaces=3
rows.push("···*")
- 2
rowis 2, so the call becomesaddRow(3, 2): two more stars and one space fewer, exactly as the pyramid widens.···*0··***1stars=3spaces=2
rows.push("··***")
- 3
rowis 3 —addRow(5, 1).···*0··***1·*****2stars=5spaces=1
rows.push("·*****")
- 4
rowis 4, which isn, soaddRow(7, 0)lays down the widest row with no padding in front of it.row++then failsrow <= nand the first loop is done.···*0··***1·*****2*******3stars=7spaces=0
rows.push("*******")
- 5
The second loop opens at
n - 1, which is 3 and not 4. Opening atnwould calladdRow(7, 0)again and the diamond would carry two widest rows.···*0··***1·*****2*******3·*****4row=3rows.length=4
rows.push("·*****")
- 6
rowcounts down through 2 and 1, calling the same helper with the same arguments the first loop used, so the rows come back out in reverse. At 0 it failsrow >= 1and the seven strings are returned.···*0··***1·*****2*******3·*****4··***5···*6row=2 then 1rows.length=5
return rows → 7 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.
- 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.
- Floyd’s triangle One counter that never resets, spilled across widening rows.