4 ms·
Here's my naive Ruby version for what it's worth. It took me way too long, perhaps because I have a nasty cold. I've been programming since 1983. If I showed up
by diego 15y ago
Here's my naive Ruby version for what it's worth. It took me way too long, perhaps because I have a nasty cold. I've been programming since 1983. If I showed up for a code interview today, I'd probably fail miserably.
def print_pascal(rows)
row=[1, 0]
(1..rows).each do |r|
next_row = Array.new(r + 1)
next_row[0] = 1
(1..row.length-1).each do |i|
next_row[i] = row[i] + row[i-1]
end
print row[0..-2], "\n"
row = next_row << 0
end
end
print_pascal(100)
- mbernstein 15y agoCouple minutes in ruby without using the knowledge of the binomial theorem or coefficients. def p(row) [1,Range.new(0, row.length - 2).map {|l| row[l] + row[l+1] }, 1].flatten end a = [1] while true a = p(a) puts a.inspect end edit: fixed formatting, sorry :(
- nileshtrivedi 15y agoHere is my version. Took me less than 5 minutes and worked the first time: def pascal(num) return [1] if num == 1 res = [] prev = [0] + pascal(num-1) + [0] (1..num).to_a.each { |i| res << (prev[i-1] + prev[i]) } return res end
- mbernstein 15y agoRecursion in this case - generally in ruby as well - is not a great idea. Also, you have quite high memory requirements: O(n^2) O(n) is quite easy in this problem.