๐Ÿš€ 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:

  1. Create two variables:

    • pattern โ†’ an empty string to accumulate the full result.
    • currentValue โ†’ a temporary variable initialized inside each row to 1.
  2. Outer loop (i from 0 to n - 1):

    • Controls the number of rows.
  3. For each row:

    • Set currentValue = 1 before entering the inner loop.
  4. Inner loop (j from 0 to i):

    • Controls the number of columns (or characters) in that row.
    • Append currentValue to pattern.
    • Flip currentValue:
      • If currentValue === 1, set it to 0.
      • Else, set it to 1.

๐Ÿ“ฅ 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));


Similar Posts