Pp Pascal (#84)

OK, so this isn’t going to win many prizes for speed or correctness
(my alignment sucks as the triangle gets bigger) but at least I tried.
Second RubyQuiz entry, from a complete numpty…

Pascal’s triangle - Rubyquiz # 84

rows = ARGV[0].to_i
@output = []

puts “Pascal’s triangle with #{rows} rows”

count = 0

1.upto(rows) do |i|
if count == 0
@output[count] = [1]
count = count.next
elsif count == 1
@output[count] = [1, 1]
count = count.next
else
line = []
line[0] = 1
1.upto(count - 1) do |index|
line[index] = (@output[count-1][index-1].to_i +
@output[count-1][index].to_i)
end
line[count] = 1
@output << line
count = count.next
end
end

maxrowlength = @output[@output.size - 1].join(" ").length

@output.each do |row|
string = row.join(" ")
puts string.center(maxrowlength)
end

Tom A. schrieb:

count = 0

1.upto(rows) do |i|
if count == 0
[…]

just some short remarks:

  1. you don’t use i
  2. count is always i-1

so you may
a) remove |i|
or
b) remove count and use i-1
or
c) change the loop to

0.upto(rows-1) do |count|

and remove all ‘count = count.next’ lines.
(and the ‘count = 0’ line)

fell free to ignore, happy coding.

Simon

Buh. Option c is so much more obvious. I was pretty much writing it as
I sketched out the algorithm, rather than going for the best Ruby.
Good points Simon, thanks.