๐ Day 15 – DSA Problem Solving: Generate Alternating Binary Triangle Pattern
๐ Problem 1: Generate Alternating Triangle
Write a function that takes a number n
and prints a triangle of size n
where each row contains alternating 1s
and 0s
, starting with 1
.
๐ก Approach:
To generate this alternating binary triangle, follow these steps:
-
Create two variables:
-
pattern
โ an empty string to accumulate the full result. -
currentValue
โ a temporary variable initialized inside each row to1
.
-
-
Outer loop (
i
from0
ton - 1
):- Controls the number of rows.
-
For each row:
- Set
currentValue = 1
before entering the inner loop.
- Set
-
Inner loop (
j
from0
toi
):- Controls the number of columns (or characters) in that row.
- Append
currentValue
topattern
. - Flip
currentValue
:- If
currentValue === 1
, set it to0
. - Else, set it to
1
.
- If
๐ฅ Input:
n = 5
๐ฅ Output:
1
10
101
1010
10101
๐งช Solution:
/**
* Generates a triangle pattern with alternating 1s and 0s
* @param {number} n - Number of rows in the pattern
* @returns {string} - The generated triangle pattern
*/
function generateAlternatingTriangle(n) {
let pattern = "";
for (let i = 0; i < n; i++) {
let currentValue = 1; // Start each row with 1
for (let j = 0; j <= i; j++) {
pattern += currentValue;
currentValue = currentValue === 1 ? 0 : 1; // Toggle value
}
pattern += "n"; // New line after each row
}
return pattern;
}
// โ
Test Case
const n = 5;
console.log(`Pattern for n = ${n}:n`);
console.log(generateAlternatingTriangle(n));