Search code examples
arraysrubymultidimensional-arraylis

2-D Array Pyramid in Ruby?


def adjacent_sum(arr)
  narr = []
  l = arr.length
  
  arr.each.with_index do  |num,index|
    if index < arr.size-1
      narr << arr[index] + arr[index+1]
    end
  end

  return narr
end

print adjacent_sum([3, 7, 2, 11]) #=> [10, 9, 13], because [ 3+7, 7+2, 2+11 ]
puts
print adjacent_sum([2, 5, 1, 9, 2, 4]) #=> [7, 6, 10, 11, 6], because [2+5, 5+1, 1+9, 9+2, 2+4]
puts

Write a method pyramid_sum that takes in an array of numbers representing the base of a pyramid. The function should return a 2D array representing a complete pyramid with the given base. To construct a level of the pyramid, we take the sum of adjacent elements of the level below.

I understand that I must make a 2-D array and use adjacent addition to build the next level of the pyramid but I don't understand the basic mechanics or thinking methodology in Ruby for two-dimensional arrays. Why am I getting array and what approach do you suggest?


Solution

  • base = [1, 2, 3, 4, 5]
    
    (base.size-1).times.with_object([base]) do |_,arr|
       arr << arr.last.each_cons(2).map(&:sum)
    end.reverse
      #=> [
      #             [48]
      #           [20, 28],
      #         [8,  12,  16],
      #       [3,  5,   7,   9],
      #     [1,  2,   3,   4,  5],
      #   ]
    

    See Enumerable#each_cons, a lovely method.