DEV Community

King coder
King coder

Posted on • Edited on

πŸš€ Day 16 - 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
Enter fullscreen mode Exit fullscreen mode

πŸ“₯ Output:

1
10
101
1010
10101
Enter fullscreen mode Exit fullscreen mode

πŸ§ͺ 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));


Enter fullscreen mode Exit fullscreen mode

//

πŸ“Œ Problem 2: Generate Hollow Square Pattern

Write a function that takes a number n and prints a hollow square of size n Γ— n using asterisks .
The border should be filled with `
`, and the inside should be filled with spaces.

πŸ’‘ Approach:

To generate this hollow square pattern, follow these steps:

  1. Create a variable:

    • pattern β†’ an empty string to accumulate the final result.
  2. Outer loop (i from 0 to n - 1):

    • Represents each row of the square.
  3. Inner loop (j from 0 to n - 1):

    • Represents each column in the current row.
    • Append * to pattern if:
      • It’s the first or last row β†’ i === 0 || i === n - 1
      • It’s the first or last column β†’ j === 0 || j === n - 1
    • Otherwise, append a space ( ) for the hollow center.
  4. After each row, append a newline character \n to move to the next line.

πŸ“₯ Input:

n = 10

Enter fullscreen mode Exit fullscreen mode

πŸ“₯ Output:

**********
*        *
*        *
*        *
*        *
*        *
*        *
*        *
*        *
**********
Enter fullscreen mode Exit fullscreen mode

πŸ§ͺ Solution:

/**
 * Generates a hollow square pattern of size n x n
 * @param {number} n - Size of the square
 * @returns {string} - The generated square pattern
 */
function generateHollowSquare(n) {
    let pattern = "";

    for (let i = 0; i < n; i++) {
        for (let j = 0; j < n; j++) {
            if (i === 0 || i === n - 1 || j === 0 || j === n - 1) {
                pattern += "*";
            } else {
                pattern += " ";
            }
        }
        pattern += "\n"; // New line after each row
    }

    return pattern;
}

// βœ… Test Case
const n = 10;
console.log(`Pattern for n = ${n}:\n`);
console.log(generateHollowSquare(n));


Enter fullscreen mode Exit fullscreen mode

πŸ“Œ Problem 3: Generate Diamond Pattern

Write a function that takes an odd number n and prints a diamond shape using asterisks (*).
The diamond should be symmetrical, with the widest point in the middle.

πŸ’‘ Approach:

To generate this diamond pattern, follow these steps:

  1. Create a variable:

    pattern β†’ an empty string to store the final result.

  2. First Part – Top Half of the Diamond (including the middle line):

    • Loop i from 1 to n, incrementing by 2.
    • For each row:
      • Add spaces: (n - i) / 2 spaces for centering.
      • Add i asterisks.
      • Add a newline \n.
  3. Second Part – Bottom Half of the Diamond:

    • Loop i from n - 2 to 1, decrementing by 2.
    • For each row:
      • Add spaces: (n - i) / 2 spaces.
      • Add i asterisks.
      • Add a newline \n.

Inside Loop 1 And Loop 2

πŸ“₯ Input:

n = 7;
Enter fullscreen mode Exit fullscreen mode

πŸ“₯ Output:

   *
  ***
 *****
*******
 *****
  ***
   *

Enter fullscreen mode Exit fullscreen mode

πŸ§ͺ Solution:

/**
 * Generates a diamond pattern of stars for a given odd number n
 * @param {number} n - Must be an odd number representing the height
 * @returns {string} - The generated diamond pattern
 */
function generateDiamond(n) {
    let pattern = "";

    // First Part: Increasing stars
    for (let i = 1; i <= n; i += 2) {
        for (let s = 0; s < (n - i) / 2; s++) {
            pattern += " ";
        }
        for (let b = 0; b < i; b++) {
            pattern += "*";
        }
        pattern += "\n";
    }

    // Second Part: Decreasing stars
    for (let i = n - 2; i >= 1; i -= 2) {
        for (let s = 0; s < (n - i) / 2; s++) {
            pattern += " ";
        }
        for (let b = 0; b < i; b++) {
            pattern += "*";
        }
        pattern += "\n";
    }

    return pattern;
}

// βœ… Test Case
const n = 7;
console.log(`Diamond pattern for n = ${n}:\n`);
console.log(generateDiamond(n));


Enter fullscreen mode Exit fullscreen mode

Top comments (0)