0
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?

Chris
  • 26,361
  • 5
  • 21
  • 42
  • 1
    Ruby does not have a concept of an n-dimensional array, but even when the term "two-dimensional array" is used loosely, it is means to be an array containing equal-size arrays, which is not the case here. – Cary Swoveland Dec 23 '21 at 21:56

1 Answers1

2
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.

Cary Swoveland
  • 106,649
  • 6
  • 63
  • 100