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

1 Answer

0 votes
# Alphabet Rangoli Generator
# --------------------------
# This program prints a geometric alphabet pattern ("rangoli") of size N.
# The pattern uses letters descending from the alphabet starting at:
#   'a' + (N - 1)
# For example, N = 5 → start letter 'e'.

# Returns the sequence of characters for a given row index.
def row_pattern(n, row)
  # Build the alphabet normally: ["a", "b", "c", ...]
  alphabet = ('a'..'z').to_a

  # Select the first n letters, but we want the *highest* letter at index 0.
  # Example: n = 5 → ["e", "d", "c", "b", "a"]
  letters = alphabet[0, n].reverse

  # Take letters down to the current row
  left_half = letters[0..row]

  # Mirror the slice except the last element
  full_row = left_half + left_half[0...-1].reverse

  full_row.join('-')
end

# Builds the full rangoli as an array of strings.
def build_rangoli(n)
  width = row_pattern(n, n - 1).length
  rows = []

  # Upper part (including middle)
  (0...n).each do |row|
    rows << row_pattern(n, row).center(width, '-')
  end

  # Lower part (mirror of upper, excluding middle)
  (n - 2).downto(0) do |row|
    rows << row_pattern(n, row).center(width, '-')
  end

  rows
end

# Prints the rangoli for a given size N.
def print_rangoli(n)
  build_rangoli(n).each { |line| puts line }
end

# Run the program with N = 5
print_rangoli(5)



=begin

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--------

=end

 



answered Jul 13 by avibootz
...