# For example, the base [1, 4, 6] gives us the following pyramid
# 15
# 5 10
# 1 4 6
def pyramid_sum(base)
pyramid = [base]
new_level = []
prev_level = []
base.length.times { |x|
prev_level = pyramid[0]
new_level = build(prev_level)
pyramid.unshift(new_level)
}
return pyramid
end
def build(level)
new_level = []
level.each_with_index { |num, index|
if index < level.length-1
new_level <<level[index] + level[index+1]
end
}
return new_level
end
print pyramid_sum([1, 4, 6]) #=> [[15], [5, 10], [1, 4, 6]]
puts
print pyramid_sum([3, 7, 2, 11]) #=> [[41], [19, 22], [10, 9, 13], [3, 7, 2, 11]]
puts
Outputs: ** [[], [15], [5, 10], [1, 4, 6]] [[], [41], [19, 22], [10, 9, 13], [3, 7, 2, 11]] **
Why is there always an extra [] (empty array) in the front of the 2D array? I have seen this many times in my results with arrays in Ruby and though it is simple I can't seem to figure out why that extra annoying array is always there? I KNOW this is simple and I may delete this question if it warrants such but why is there an extra array element in the front of my array? It seems like to merely create an array is it always have an extra element in it and I can't "truly" modify it because everything in Ruby is an object anyways.