如何在Ruby中循环遍历数组并在每次迭代后删除第一个元素



我正在做一个关于ruby课程的项目。我要实现一种方法,该方法考虑一系列股票价格,并返回最佳买入日和最佳卖出日。每个价格(数组元素(的索引都是当天的价格。我想解决这个问题的方法是,首先将数组复制到一个新的绑定中,然后映射到原始数组上,在原始数组内部映射到复制的数组中,并在循环结束后删除第一个元素,即,解决一个人不能在第10天买入而在第1天卖出的情况。

这是我写的代码:

def stock_picker(stock_price)
#copying the array into a new binding
stock_array = []
stock_array.replace(stock_price)
stock_price.map do |buy|
stock_array.map do |sell|
sell - buy
end
#deleting the first element
stock_array.shift
end
end
array = stock_picker([17,3,6,9,15,8,6,1,10])

这是我收到的结果:

[17, 3, 6, 9, 15, 8, 6, 1, 10]

这就是我期望得到的:

[[0, -14, -11, -8, -2, -9, -11, -16, -7], [0, 3, 6, 12, 5, 3, -2, 7], [0, 3, 9, 2, 0, -5, 4], [0, 6, -1, -3, -8, 1], [0, -7, -9, -14, -5], [0, -2, -7, 2], [0, -5, 4], [0, 9], [0]]

首先,我不明白为什么每次都要移动第一个元素。但这里有一些备注可以帮助您:

  • .map块中,返回最后一个值。在这种情况下是CCD_ 2。这就是为什么您会得到初始数组的结果。因为它在数组上迭代,每次都返回第一个元素,但由于每次都移动数组,所以只转到下一个值,然后再转到下一值,依此类推…

  • 您可以简单地用stock_price.dup复制它,而不是使用新的阵列并用stock_price替换它

你会有这样的东西:

def stock_picker(stock_price)
stock_price.dup.map do |buy|
res = stock_price.map do |sell|
sell - buy
end
stock_price.shift
res
end
end

但是,上面的例子再次返回了您想要的,我不明白为什么。。。

以下是获得预期输出的简单循环方法:

代码

array = [17,3,6,9,15,8,6,1,10]
arr = [17,3,6,9,15,8,6,1,10]
answer = []
for i in array 
temp = []
arr.each do |x| 
temp.push(x - i)
end 
arr.shift
answer.push(temp)
end 
print answer

将给出

输出:

[[0, -14, -11, -8, -2, -9, -11, -16, -7], [0, 3, 6, 12, 5, 3, -2, 7], [0, 3, 9, 2, 0, -5, 4], [0, 6, -1, -3, -8, 1], [0, -7, -9, -14, -5], [0, -2, -7, 2], [0, -5, 4], [0, 9], [0]]

尝试以下

def stock_picker(stock_price)
#copying the array into a new binding
stock_array = []
stock_array.replace(stock_price)

stock_price.map do |buy|
result = stock_array.map {|sell| sell - buy }
stock_array.shift
p result
end
end
array = stock_picker([17,3,6,9,15,8,6,1,10])

输出

[0, -14, -11, -8, -2, -9, -11, -16, -7]
[0, 3, 6, 12, 5, 3, -2, 7]
[0, 3, 9, 2, 0, -5, 4]
[0, 6, -1, -3, -8, 1]
[0, -7, -9, -14, -5]
[0, -2, -7, 2]
[0, -5, 4]
[0, 9]
[0]

最新更新