How to create an alphabet rangoli (geometric and character pattern) of size N in TypeScript

1 Answer

0 votes
// Function to generate and print the alphabet rangoli of size N
function printAlphabetRangoli(n: number): void {
    if (n <= 0) return;

    // Total width of the grid based on character and hyphen spacing
    const totalWidth: number = 4 * n - 3;

    // Loop from -(n-1) to (n-1) to handle top/bottom symmetry mathematically
    for (let i: number = -(n - 1); i <= (n - 1); i++) {
        const currentRowDist: number = Math.abs(i); // Distance from the center row

        let lineChars: string = "";

        // 1. Build the left/descending side of characters (e.g., e -> d -> c)
        for (let j: number = 0; j < n - currentRowDist; j++) {
            const ch: string = String.fromCharCode("a".charCodeAt(0) + n - 1 - j);
            lineChars += ch;
        }

        // 2. Build the right/ascending side of characters (e.g., d -> e)
        for (let j: number = n - currentRowDist - 2; j >= 0; j--) {
            const ch: string = String.fromCharCode("a".charCodeAt(0) + n - 1 - j);
            lineChars += ch;
        }

        // 3. Insert hyphens between characters
        let standardRow: string = "";
        for (let k: number = 0; k < lineChars.length; k++) {
            standardRow += lineChars[k];
            if (k !== lineChars.length - 1) {
                standardRow += "-";
            }
        }

        // 4. Calculate necessary hyphen padding for centering
        const totalPadding: number = totalWidth - standardRow.length;
        const sideHyphens: string = "-".repeat(totalPadding / 2);

        // 5. Print the complete constructed row
        console.log(sideHyphens + standardRow + sideHyphens);
    }
}

// Usage
const n: number = 5;
printAlphabetRangoli(n);


/*
run:

--------e--------
------e-d-e------
----e-d-c-d-e----
--e-d-c-b-c-d-e--
e-d-c-b-a-b-c-d-e
--e-d-c-b-c-d-e--
----e-d-c-d-e----
------e-d-e------
--------e--------

*/

 



answered 1 day ago by avibootz
...