Building a Pyramid Shape in JavaScript

In this blog post, we’ll explore how to create a pyramid shape using the # character in JavaScript. This exercise is a great way to practice loops, string manipulation, and understanding patterns in coding.

Problem Statement

Write a function that accepts a positive integer N and prints a pyramid shape with N levels using the # character. The pyramid should be center-aligned with spaces on both sides. Here are a few examples:

pyramid(2);
// Output:
// ' # '
// '###'

pyramid(3);
// Output:
// '  #  '
// ' ### '
// '#####'

pyramid(4);
// Output:
// '   #   '
// '  ###  '
// ' ##### '
// '#######'

Understanding the Pattern

To solve this problem, let’s break down how a pyramid is constructed:

  • For a given level i, the number of # characters is (2 * i - 1), which gives the correct odd number sequence (1, 3, 5, …).
  • The total width of each line is 2 * n - 1, where n is the total number of levels. This ensures the pyramid is centered.

Solution Approach

We’ll use two loops:

  1. Outer Loop: Iterates from 1 to N (inclusive), representing the current level.
  2. Inner Calculations:
  • Determine the number of # characters as (2 * i - 1).
  • Calculate the number of spaces on each side to make the line centered.

Here’s the JavaScript code to achieve this:

function pyramid(n) {
  const totalWidth = 2 * n - 1;

  for (let i = 1; i <= n; i++) {
    // Calculate the number of `#` characters for the current level
    const numHashes = 2 * i - 1;

    // Calculate the number of spaces on each side
    const numSpaces = (totalWidth - numHashes) / 2;

    // Construct the line with spaces on both sides and `#` in the middle
    const line = ' '.repeat(numSpaces) + '#'.repeat(numHashes) + ' '.repeat(numSpaces);

    console.log(line);
  }
}

// Test cases
pyramid(2);
//  ' # '
//  '###'

pyramid(3);
//  '  #  '
//  ' ### '
//  '#####'

pyramid(4);
//  '   #   '
//  '  ###  '
//  ' ##### '
//  '#######'

Explanation of the Code

  1. Calculating totalWidth: This represents the total width of each line in the pyramid. It is equal to 2 * n - 1, ensuring that the widest line (the base of the pyramid) fits properly.
  2. Number of Hashes and Spaces:
  • For each level i, we calculate the number of # characters (numHashes) using the formula 2 * i - 1, which gives an increasing sequence of odd numbers.
  • The number of spaces on each side (numSpaces) is determined by (totalWidth - numHashes) / 2 to center the # characters.
  1. Constructing the Line:
  • We build the line using ' '.repeat(numSpaces) for the left padding, followed by '#'.repeat(numHashes) for the middle, and another ' '.repeat(numSpaces) for the right padding.
  • The resulting string is then logged to the console.

Exploring Variations

To deepen your understanding, try modifying the exercise:

  1. Inverted Pyramid: Create a pyramid that starts with the widest level at the top and narrows down.
  2. Hollow Pyramid: Only the borders of the pyramid are made of #, with spaces inside.
  3. Diamond Shape: Combine an upward and a downward pyramid to form a diamond.

Key Takeaways

  1. Pattern Recognition: Understanding how to calculate the number of characters and spaces is essential for solving pattern-based problems.
  2. Loops and String Manipulation: Using loops with string methods like repeat() helps in constructing patterns easily.
  3. Modular Code: Breaking down the problem into smaller parts (calculating hashes, spaces, and constructing the line) makes the solution clearer and easier to understand.

Conclusion

Building a pyramid shape with JavaScript is an excellent way to practice basic programming concepts and think critically about pattern generation. This type of problem can be a stepping stone to more complex coding challenges. Try it out, explore variations, and share your solutions!

Leave a Reply

Your email address will not be published. Required fields are marked *