Recommended Posts

DSA (Medium) - General - Print A Diamond Shape (Typescript, Python & Rust)

1 comment

simplestack0.312 months agoPeakD10 min read


https://files.peakd.com/file/peakd-hive/simplestack/AKFAAYwC7MQupaPzNne2j8DdL1orztntzeKs4fQh3z4kp4PAoy4dbwf2w6D8kQk.png

Given the following shape:

[LOG]: "     A" 
[LOG]: "    B B" 
[LOG]: "   C   C" 
[LOG]: "  D     D" 
[LOG]: " E       E" 
[LOG]: "F         F" 
[LOG]: " E       E" 
[LOG]: "  D     D" 
[LOG]: "   C   C" 
[LOG]: "    B B" 
[LOG]: "     A"

Print it to the console.

There were no specific params required but in this case let's do it for an arbitrary number of letters.

Explanation

Okay, imagine you want to draw a diamond shape using letters. You give me the top half of the letters, like A, B, C. My job is to figure out the rest and print the whole diamond.
Here's the general idea in simple steps (like a recipe):

🔹Get the Full Letter List:
🔸🔸You give me the first half of the letters.
🔸🔸I take those letters and make a copy of them.
🔸🔸I reverse the copy.
🔸🔸I remove the very first letter from the reversed copy (so we don't have the middle letter twice).
🔸🔸I then stick the original letters and the modified reversed letters together. Now I have the complete list of letters for the diamond, going from top to bottom. For example, if you gave me A, B, C, I'd end up with A, B, C, B, A.

🔹Figure Out the Middle:
🔸🔸I count how many letters are in my complete list. Let's say there are 5 letters.
🔸🔸I find the middle position. In a list of 5, the middle is at index 2 (starting from 0). This helps me know how many spaces to put at the beginning of each line.

🔹Draw Each Line:
🔸🔸I go through each letter in my complete list, one by one, from the beginning to the end. For each letter, I'm going to print a line.

🔹Spaces at the Beginning:
🔸🔸For each line, I calculate how many spaces I need at the beginning to make the diamond shape. The lines at the top and bottom need more spaces, and the line in the middle needs no spaces. I use the middle position I found earlier to figure this out. The further a letter is from the middle, the more spaces it gets at the start.
🔸🔸I print those spaces.

🔹The First Letter:
🔸🔸I print the current letter from my list.

🔹Spaces in the Middle (if needed):
🔸🔸If I'm not on the very first or the very last line (because those only have one letter), I need to put spaces between the two identical letters in that row.
🔸🔸I calculate how many spaces go in the middle. The lines closer to the middle have more spaces in between.
🔸🔸I print those middle spaces.

🔹The Second Letter (if needed):
🔸🔸If I added middle spaces, I now print the same letter again to complete the row.

🔹New Line:
🔸🔸After printing the spaces and the letter(s) for the current step, I move to the next line.

function printDiamondPattern(firstHalfOfLetters):
  otherHalf = reverse(copy(firstHalfOfLetters))
  removeFirstElement(otherHalf)
  completeLetters = combine(firstHalfOfLetters, otherHalf)
  numberOfRows = length(completeLetters)
  middleRowIndex = floor(numberOfRows / 2)

  for each index 'i' from 0 to numberOfRows - 1:
    currentLetter = completeLetters[i]
    leadingSpaces = absoluteValue(middleRowIndex - i)
    line = ""

    add leadingSpaces to line

    add currentLetter to line

    if i is not 0 and i is not numberOfRows - 1:
      innerSpaces = 2 * (middleRowIndex - leadingSpaces) - 1
      add innerSpaces to line
      add currentLetter to line

    print line

Implementations

🐍Python

def print_diamond_pattern(letters: list[str]) -> None:
    """
    Prints a diamond pattern to the console based on the provided array of letters.
    The function takes the first half of the diamond's letters and automatically
    generates the second half to create a symmetrical diamond shape.

    Args:
        letters: An array of strings representing the first half of the diamond's letters
                 in ascending order (e.g., ['A', 'B', 'C']).
    """
    # Creates the reversed version of the input array to form the bottom half
    # of the diamond.
    other_half: list[str] = letters[::-1]

    # Removes the first element of the reversed array to avoid duplication
    # of the middle letter in the complete diamond.
    if other_half:
        other_half.pop(0)

    # Combines the original letters and the reversed (shifted) letters to form
    # the complete sequence for the diamond.
    complete_letters: list[str] = letters + other_half

    # Determines the total number of rows in the diamond.
    n: int = len(complete_letters)

    # Calculates the index of the middle row of the diamond. This is used to
    # determine the number of leading spaces for each row.
    middle_index: int = n // 2

    # Iterates through each row of the diamond.
    for i in range(n):
        # Initializes an empty string to build the current row.
        line: str = ""

        # Calculates the number of leading spaces required for the current row
        # to center the diamond. The number of spaces increases as the row gets
        # closer to the top and bottom edges.
        num_spaces: int = abs(middle_index - i)

        # Adds the leading spaces to the current line.
        line += " " * num_spaces

        # Adds the letter for the current row (the first letter of the pair, or the
        # single letter for the top and bottom rows).
        line += complete_letters[i]

        # Checks if the current row is not the very first or the very last row.
        # These rows only contain a single letter.
        if i != 0 and i != n - 1:
            # Calculates the number of spaces between the two identical letters in
            # the current row. This number decreases as the row gets closer to the
            # top and bottom edges.
            inner_spaces: int = 2 * (middle_index - num_spaces) - 1

            # Adds the inner spaces to the current line.
            line += " " * inner_spaces

            # Adds the second identical letter to the current line.
            line += complete_letters[i]

        # Prints the complete line (row) to the console.
        print(line)

# Example usage of the print_diamond_pattern function with an initial array
# representing the first half of the diamond.
print_diamond_pattern(['A', 'B', 'C', 'D', 'E', 'F'])

🟦Typescript

/**
 * Prints a diamond pattern to the console based on the provided array of letters.
 * The function takes the first half of the diamond's letters and automatically
 * generates the second half to create a symmetrical diamond shape.
 *
 * @param letters An array of strings representing the first half of the diamond's letters
 * in ascending order (e.g., ['A', 'B', 'C']).
 */
function printDiamondPattern(letters: string[]): void {
  /**
   * Creates the reversed version of the input array to form the bottom half
   * of the diamond.
   */
  const otherHalf: string[] = [...letters].reverse();

  /**
   * Removes the first element of the reversed array to avoid duplication
   * of the middle letter in the complete diamond.
   */
  otherHalf.shift();

  /**
   * Combines the original letters and the reversed (shifted) letters to form
   * the complete sequence for the diamond.
   */
  const completeLetters: string[] = [...letters, ...otherHalf];

  /**
   * Determines the total number of rows in the diamond.
   */
  const n: number = completeLetters.length;

  /**
   * Calculates the index of the middle row of the diamond. This is used to
   * determine the number of leading spaces for each row.
   */
  const middleIndex: number = Math.floor(n / 2);

  /**
   * Iterates through each row of the diamond.
   */
  for (let i: number = 0; i < n; i++) {
    /**
     * Initializes an empty string to build the current row.
     */
    let line: string = "";

    /**
     * Calculates the number of leading spaces required for the current row
     * to center the diamond. The number of spaces increases as the row gets
     * closer to the top and bottom edges.
     */
    const numSpaces: number = Math.abs(middleIndex - i);

    /**
     * Adds the leading spaces to the current line.
     */
    for (let j: number = 0; j < numSpaces; j++) {
      line += " ";
    }

    /**
     * Adds the letter for the current row (the first letter of the pair, or the
     * single letter for the top and bottom rows).
     */
    line += completeLetters[i];

    /**
     * Checks if the current row is not the very first or the very last row.
     * These rows only contain a single letter.
     */
    if (i !== 0 && i !== n - 1) {
      /**
       * Calculates the number of spaces between the two identical letters in
       * the current row. This number decreases as the row gets closer to the
       * top and bottom edges.
       */
      const innerSpaces: number = 2 * (middleIndex - numSpaces) - 1;

      /**
       * Adds the inner spaces to the current line.
       */
      for (let k: number = 0; k < innerSpaces; k++) {
        line += " ";
      }

      /**
       * Adds the second identical letter to the current line.
       */
      line += completeLetters[i];
    }

    /**
     * Prints the complete line (row) to the console.
     */
    console.log(line);
  }
}

/**
 * Example usage of the printDiamondPattern function with an initial array
 * representing the first half of the diamond.
 */
printDiamondPattern(['A', 'B', 'C', 'D', 'E', 'F']);

🦀Rust

fn print_diamond_pattern(letters: &[&str]) {
    // Creates the reversed version of the input array to form the bottom half
    // of the diamond.
    let mut other_half: Vec<&str> = letters.iter().rev().cloned().collect();

    // Removes the first element of the reversed array to avoid duplication
    // of the middle letter in the complete diamond.
    if !other_half.is_empty() {
        other_half.remove(0);
    }

    // Combines the original letters and the reversed (shifted) letters to form
    // the complete sequence for the diamond.
    let complete_letters: Vec<&str> = letters.iter().chain(other_half.iter()).cloned().collect();

    // Determines the total number of rows in the diamond.
    let n: usize = complete_letters.len();

    // Calculates the index of the middle row of the diamond. This is used to
    // determine the number of leading spaces for each row.
    let middle_index: usize = n / 2;

    // Iterates through each row of the diamond.
    for i in 0..n {
        // Initializes an empty string to build the current row.
        let mut line: String = String::new();

        // Calculates the number of leading spaces required for the current row
        // to center the diamond. The number of spaces increases as the row gets
        // closer to the top and bottom edges.
        let num_spaces: usize = (middle_index as isize - i as isize).abs() as usize;

        // Adds the leading spaces to the current line.
        for _ in 0..num_spaces {
            line.push(' ');
        }

        // Adds the letter for the current row (the first letter of the pair, or the
        // single letter for the top and bottom rows).
        line.push_str(complete_letters[i]);

        // Checks if the current row is not the very first or the very last row.
        // These rows only contain a single letter.
        if i != 0 && i != n - 1 {
            // Calculates the number of spaces between the two identical letters in
            // the current row. This number decreases as the row gets closer to the
            // top and bottom edges.
            let inner_spaces: usize = 2 * (middle_index - num_spaces) - 1;

            // Adds the inner spaces to the current line.
            for _ in 0..inner_spaces {
                line.push(' ');
            }

            // Adds the second identical letter to the current line.
            line.push_str(complete_letters[i]);
        }

        // Prints the complete line (row) to the console.
        println!("{}", line);
    }
}

fn main() {
    // Example usage of the print_diamond_pattern function with an initial array
    // representing the first half of the diamond.
    print_diamond_pattern(&["A", "B", "C", "D", "E", "F"]);
}

If you liked this content I’d appreciate an upvote or a comment. That helps me improve the quality of my posts as well as getting to know more about you, my dear reader.

Muchas gracias!

Follow me for more content like this.

X | PeakD | Rumble | YouTube | Linked In | GitHub | PayPal.me | Medium

Down below you can find other ways to tip my work.

BankTransfer: "710969000019398639", // CLABE
BAT: "0x33CD7770d3235F97e5A8a96D5F21766DbB08c875",
ETH: "0x33CD7770d3235F97e5A8a96D5F21766DbB08c875",
BTC: "33xxUWU5kjcPk1Kr9ucn9tQXd2DbQ1b9tE",
ADA: "addr1q9l3y73e82hhwfr49eu0fkjw34w9s406wnln7rk9m4ky5fag8akgnwf3y4r2uzqf00rw0pvsucql0pqkzag5n450facq8vwr5e",
DOT: "1rRDzfMLPi88RixTeVc2beA5h2Q3z1K1Uk3kqqyej7nWPNf",
DOGE: "DRph8GEwGccvBWCe4wEQsWsTvQvsEH4QKH",
DAI: "0x33CD7770d3235F97e5A8a96D5F21766DbB08c875"

Comments

Sort byBest