Binary (0–1) triangle
Given a row count n, return a triangle of alternating 1s and 0s as an array of n strings, row i holding i characters. The characters alternate along a row, and a row begins with 1 when its number is odd and 0 when it is even.
Examples
Example 1
- Input
- n = 5
- Output
1 01 101 0101 10101
Rows 1, 3 and 5 open on["1","01","101","0101","10101"]1; rows 2 and 4 open on0.
Example 2
- Input
- n = 2
- Output
1 01
Two rows, the odd one opening on["1","01"]1and the even one on0.
The Code
function binaryTriangle(n) {
const rows = [];
for (let row = 1; row <= n; row++) {
let line = "";
for (let col = 1; col <= row; col++) {
line += (row + col) % 2 === 0 ? "1" : "0";
}
rows.push(line);
}
return rows;
}
binaryTriangle(5);The first 19 calls, of 27. This one does not fit on a page.
Explanation
Moving one column flips the character, and so does moving one row. A position’s digit therefore depends on the two counts together, never on what the position before it was.
- 1
rowis 1 andcolis 1, sorow + colis 2.(row + col) % 2 === 0holds, and the"1"side of the conditional is appended. The inner loop stops there, becausecolis alreadyrow.10row=1row + col=2
rows.push("1")
- 2
rowis 2. Atcol1 the sum is 3, which is odd, so the row opens on"0"; atcol2 it is 4 and the character is"1". Stepping one column changes the sum by one, which is what makes a row alternate.10011row=2row + col=3 then 4
rows.push("01")
- 3
rowis 3. Stepping one row also changes the sum by one, socol1 now gives 4 and the row opens on"1"— the opposite of the row above it.100111012row=3row + col=4 … 6
rows.push("101")
- 4
rowis 4, so the sums run 5 to 8 and the row opens on"0"again. No digit is ever read back: each position is decided entirely by where it sits.10011101201013row=4row + col=5 … 8
rows.push("0101")
- 5
rowis 5 and the sums run 6 to 10, giving"10101".row++then failsrow <= nand the five strings are returned.10011101201013101014row=5row + col=6 … 10
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.