Ruby 中的二维阵列金字塔?
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.
我明白我必须做一个二维数组并使用相邻的加法来构建金字塔的下一层但是我不明白Ruby中二维的基本机制或思维方法阵列。为什么我得到数组,你建议采用什么方法?
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],
# ]
参见 Enumerable#each_cons,一个可爱的方法。
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.
我明白我必须做一个二维数组并使用相邻的加法来构建金字塔的下一层但是我不明白Ruby中二维的基本机制或思维方法阵列。为什么我得到数组,你建议采用什么方法?
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],
# ]
参见 Enumerable#each_cons,一个可爱的方法。