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编写一个
pyramid_sum方法,它接受一个代表金字塔底部的数字数组。该函数应该返回一个二维数组,表示具有给定基的完整金字塔。为了构造金字塔的一个层次,我们取下面层次的相邻元素之和。
我知道我必须制作一个二维数组,并使用相邻的加法来构建金字塔的下一层,但我不了解Ruby中用于二维数组的基本机制或思想方法。为什么我得到了排列和你建议什么方法?
发布于 2021-12-23 21:40:34
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],
# ]看看缺点,一个可爱的方法。
https://stackoverflow.com/questions/70464801
复制相似问题