检查数组中的2个数字在Ruby中是否等于0

Tsc*_*ott 0 ruby arrays

我已经解决了这个问题了几个小时,我不明白为什么我无法使其正常运行。此方法的最终结果是将两个数字加在一起等于零。这是我的代码:

def two_sums(nums)
    i = 0
    j = -1
    while i < nums.count
        num_1 = nums[i]
        while j < nums.count
        num_2 = nums[j]
            if num_1 + num_2 == 0
                return "There are 2 numbers that sum to zero & they are #{num_1} and #{num_2}."
            else
                return "Nothing adds to zero."
            end             
        end
    i += 1
    j -= 1
    end
end
Run Code Online (Sandbox Code Playgroud)

我遇到的问题是,除非数组中的第一个和最后一个数字是相同数字的正负,否则它将始终返回false。

例如,如果我有一个[1,4,6,-1,10]的数组,那么它应该恢复为真。我确定我的2 while语句是造成这种情况的原因,但我想不出一种解决方法。如果有人可以指出正确的方向,那将会有所帮助。

spi*_*ann 5

您可以找到第一个加起来为0的对,如下所示:

nums.combination(2).find { |x, y| x + y == 0 }
#=> returns the first matching pair or nil
Run Code Online (Sandbox Code Playgroud)

或者,如果您要选择所有总计为0的对,请执行以下操作:

nums.combination(2).select { |x, y| x + y == 0 }
#=> returns all matching pairs or an empty array
Run Code Online (Sandbox Code Playgroud)

因此,您可以像这样实现您的方法:

def two_sums(nums)
  pair = nums.combination(2).find { |x, y| x + y == 0 }
  if pair
    "There are 2 numbers that sum to zero & they are #{pair.first} and #{pair.last}."
  else
    "Nothing adds to zero."
  end
end    
Run Code Online (Sandbox Code Playgroud)

或者,如果您要查找所有对:

def two_sums(nums)
  pairs = nums.combination(2).select { |x, y| x + y == 0 }
  if pairs.empty?
    "Nothing adds to zero."
  else
    "The following pairs sum to zero: #{pairs}..."
  end
end    
Run Code Online (Sandbox Code Playgroud)