๐ 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 (
ifrom0ton - 1):- Controls the number of rows.
-
For each row:
- Set
currentValue = 1before entering the inner loop.
- Set
-
Inner loop (
jfrom0toi):- Controls the number of columns (or characters) in that row.
- Append
currentValuetopattern. - 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));