检查数组中的2个数字在Ruby中是否等于0 [英] Checking to see if 2 numbers in array sum to 0 in Ruby

查看:75
本文介绍了检查数组中的2个数字在Ruby中是否等于0的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I've been going at this problem for a few hours, and I can't see why I can't get it to run properly. The end game to this method is having 2 numbers in an array equaling zero when added together. Here is my code:

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

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

The problem I'm having is unless the first and last number in the array are the positive and negative of the same number, this will always return false.

例如,如果我有一个[1,4,6,-1,10]的数组,它应该返回true。我确定我的2时声明是造成这种情况的原因,但我想不出一种解决方法。如果有人可以向我指出正确的方向,那将会有所帮助。

For example, if I had an array that was [1, 4, 6, -1, 10], it should come back true. I'm sure my 2 while statement is the cause of this, but I can't think of a way to fix it. If someone could point me in the right direction, that would be helpful.

推荐答案

您可以找到第一对0像这样:

You can find the first pair that adds up to 0 like this:

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

或者如果要选择所有总计为0的对:

Or if you want to select all pairs that add up to 0:

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

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

Therefore you can implement your method like this:

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    

或者如果要查找所有对:

Or if you want to find all pairs:

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    

这篇关于检查数组中的2个数字在Ruby中是否等于0的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆