我正在尝试编写一个函数,它可以为您提供完成连续数组所需的数字。例如,如果我们有数组[3,5,7],则函数应该返回2(即4,6)。我已经提出了下面的代码,但它给了我以下错误?有什么想法吗?谢谢!
def consecutive(*arr)
sorted = arr.sort
current_count = 0
sorted.each_index do |i|
next if i == sorted.length
difference = arr[i+1] - arr[i] - 1
current_count += difference
end
current_count
end
这就是错误:
undefined method `-' for nil:NilClass
(repl):9:in `block in Consecutive'
(repl):6:in `each_index'
(repl):6:in `Consecutive'
(repl):16:in `<main>'
答案 0 :(得分:1)
如果您的数组是arr
,则可以执行以下操作:
arr = [3,1,5,7,8]
f,l = arr.minmax
#=> [1, 8]
l-f+1 - arr.size
#=> 3
答案 1 :(得分:0)
arr[i + 1]
的最后一次传递中, each_index
将为零。您可以使用each_cons(2)
代替处理指数:
def Consecutive(arr)
sorted = arr.sort
current_count = 0
sorted.each_cons(2) do |a, b|
difference = b - a - 1
current_count += difference
end
current_count
end
Consecutive([3,5,7])
=> 2