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

1 Answer

0 votes
program AlphabetRangoli;

// Function to generate and print the alphabet rangoli of size N
procedure printAlphabetRangoli(n: Integer);
var
    total_width: Integer;
    i, j, current_row_dist: Integer;
    line_chars, standard_row, side_hyphens: string;
    k: Integer;
    total_padding: Integer;
begin
    if n <= 0 then Exit;

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

    // Loop from -(n-1) to (n-1) to handle top/bottom symmetry mathematically
    for i := -(n - 1) to (n - 1) do
    begin
        current_row_dist := Abs(i); // Distance from the center row

        line_chars := '';

        // 1. Build the left/descending side of characters (e.g., e -> d -> c)
        for j := 0 to n - current_row_dist - 1 do
            line_chars := line_chars + Chr(Ord('a') + n - 1 - j);

        // 2. Build the right/ascending side of characters (e.g., d -> e)
        for j := n - current_row_dist - 2 downto 0 do
            line_chars := line_chars + Chr(Ord('a') + n - 1 - j);

        // 3. Insert hyphens between characters
        standard_row := '';
        for k := 1 to Length(line_chars) do
        begin
            standard_row := standard_row + line_chars[k];
            if k <> Length(line_chars) then
                standard_row := standard_row + '-';
        end;

        // 4. Calculate necessary hyphen padding for centering
        total_padding := total_width - Length(standard_row);
        side_hyphens := StringOfChar('-', total_padding div 2);

        // 5. Print the complete constructed row
        WriteLn(side_hyphens + standard_row + side_hyphens);
    end;
end;

var
    n: Integer;

begin
    n := 5;

    printAlphabetRangoli(n);
end.



(*
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 Jul 12 by avibootz
edited Jul 12 by avibootz
...