[英]Merging two sorted arrays not working
Trying to solve a problem involving merging two sorted arrays without using the sort method. 试图解决涉及不使用sort方法合并两个排序数组的问题。 Here's my code so far: 到目前为止,这是我的代码:
def combine(arr1, arr2)
result = []
i = 0
arr1.each do |num|
while num > arr2[i] && arr2[i] != nil
result << arr2[i]
i += 1
end
result << num
end
result
end
When I run this with [1, 9, 10, 12], [2, 5, 6, 8]
as the two arguments, it gives me a comparison of Fixnum
to nil
error and I can't wrap my head around it. 当我以[1, 9, 10, 12], [2, 5, 6, 8]
Fixnum
[1, 9, 10, 12], [2, 5, 6, 8]
作为两个参数运行此函数时,它为我提供了Fixnum
与nil
错误的比较,并且我无法将其包围。 It seems like an easy fix but nothing seems to be working. 似乎很容易解决,但似乎无济于事。
while num > arr2[i] && arr2[i] != nil
You are using the wrong condition. 您使用了错误的条件。 According to the short circuit rule of &&
, put the check for nil
on the left: 根据&&
短路规则,将检查nil
放在左侧:
while arr2[i] != nil && num > arr2[i]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.