Skip to content

Instantly share code, notes, and snippets.

@veganstraightedge
Last active July 30, 2025 07:03
Show Gist options
  • Save veganstraightedge/eb8166c10a80f909e6632dea8d23c34e to your computer and use it in GitHub Desktop.
Save veganstraightedge/eb8166c10a80f909e6632dea8d23c34e to your computer and use it in GitHub Desktop.
After watching a couple Numberphile videos on YouTube about Catalan Numbers and Pascal's Triangle, I wrote a Pascal's Triangle implementation in Ruby as a fun little exercise. https://youtu.be/fczN0BCx0xs https://youtu.be/0iMtlus-afo
def pascals_triangle total_rows=3, start_value=1
rows = []
(total_rows + 1).times do |current_row|
if current_row == 1
rows << [nil, start_value]
next
end
row = [nil]
current_row.times do |item|
previous_row = rows[current_row - 1]
left_parent = previous_row[item].to_i
right_parent = previous_row[item + 1].to_i
row << left_parent + right_parent
end
rows << row
end
rows.shift # delete the implied 0, 0 row
rows.each &:compact! # delete the placeholder leading nil
end
def format_triangle triangle
triangle_width = triangle.last.length * 2 - 1
# for centering numbers as the get wider than one digit
widest_number = triangle.last.max.to_s.length
padding = ' ' * widest_number
triangle.map.with_index do |row, index|
inner_width = row.length * 2 - 1
outer_width = (triangle_width - inner_width) / 2
outer_padding = Array.new outer_width, padding
padded_row = row.flat_map { |item| [item.to_s.center(widest_number), padding] }
padded_row.pop
[outer_padding, padded_row, outer_padding].flatten.join
end
end
def formatted_pascals_triangle total_rows=3, start_value=1
format_triangle(pascals_triangle total_rows, start_value)
end
##########################################
# to show 2D array structure
pascals_triangle(1).each { pp it }
puts
pascals_triangle(2).each { pp it }
puts
pascals_triangle(3).each { pp it }
puts
pascals_triangle(10).each { pp it }
puts
# to show printing visually formatted as a triangle too
puts formatted_pascals_triangle 10
[1]
[1]
[1, 1]
[1]
[1, 1]
[1, 2, 1]
[1]
[1, 1]
[1, 2, 1]
[1, 3, 3, 1]
[1, 4, 6, 4, 1]
[1, 5, 10, 10, 5, 1]
[1, 6, 15, 20, 15, 6, 1]
[1, 7, 21, 35, 35, 21, 7, 1]
[1, 8, 28, 56, 70, 56, 28, 8, 1]
[1, 9, 36, 84, 126, 126, 84, 36, 9, 1]
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
1 6 15 20 15 6 1
1 7 21 35 35 21 7 1
1 8 28 56 70 56 28 8 1
1 9 36 84 126 126 84 36 9 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment