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

1 Answer

0 votes
public class AlphabetRangoli {

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

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

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

            StringBuilder line_chars = new StringBuilder();

            // 1. Build the left/descending side of characters (e.g., e -> d -> c)
            for (int j = 0; j < n - current_row_dist; ++j) {
                line_chars.append((char) ('a' + n - 1 - j));
            }

            // 2. Build the right/ascending side of characters (e.g., d -> e)
            for (int j = n - current_row_dist - 2; j >= 0; --j) {
                line_chars.append((char) ('a' + n - 1 - j));
            }

            // 3. Insert hyphens between characters
            StringBuilder standard_row = new StringBuilder();
            for (int k = 0; k < line_chars.length(); ++k) {
                standard_row.append(line_chars.charAt(k));
                if (k != line_chars.length() - 1) {
                    standard_row.append("-");
                }
            }

            // 4. Calculate necessary hyphen padding for centering
            int total_padding = total_width - standard_row.length();
            String side_hyphens = "-".repeat(total_padding / 2);

            // 5. Print the complete constructed row
            System.out.println(side_hyphens + standard_row + side_hyphens);
        }
    }

    public static void main(String[] args) {
        int n = 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 2 days ago by avibootz
edited 2 days ago by avibootz
...