[QUIZ] pp Pascal (#84)

Hello everyone! This is my first quiz submission.

I suppose it’s a little verbose, but I feel it’s clever enough. I do
the straightforward, plain-vanilla recursive building of the triangle
right from the Array constructor, which is kinda cool, then extend the
Array class to print it out. (The to_centered_spaced_string method
really only works on a fairly specific subset of 2D arrays,

And, thanks for the quizzes! I have enjoyed the past entries greatly.

Devin Chalmers

PS - sorry for the 81-char line. I hate it too. :slight_smile:

==== pp_pascal.rb


def pascal_cell(row, col)
return 1 if col == 0 or col == row
return pascal_cell(row - 1, col) + pascal_cell(row - 1, col - 1)

def pascal_array(depth)
Array.new(depth) {|i| Array.new(i + 1){|j| pascal_cell(i, j)}}

class Array
def to_centered_spaced_string
cell_width = self.flatten.collect{|val| val.to_s.size}.max + 2
row_width = self.collect{|row| row.size}.max * cell_width
rows = Array.new(self.size) do |i|
return rows.join("\n")

puts pascal_array(ARGV[0].to_i).to_centered_spaced_string

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs