我正在尝试查找 n 是否作为所传递数组中任何两个数字的和而存在,如果返回 true 否则为 false ,我的代码存在的问题是 inject 没有按照我的意愿进行迭代。我在做什么错?
I am trying to find whether n exists as a sum of any two numbers in the passed array if so return true else false, the problem with my code is that inject is not iterating as I want it to. What am I doing wrong?
def sum_to_n?(array,n) array.each do |i| array.inject(i) do |memo,var| if memo + var == n return true else return false end end end end puts sum_to_n?([1,2,3,4,5],9)推荐答案
这里是一种方法:
def sum_to_n?(a,n) !!a.find{|e| a.include?(n-e)} end a = [1,2,3,4,5] sum_to_n?(a,9) # => true sum_to_n?(a,11) # => false如果要获取这两个元素:
If you want to get those 2 elements:
def sum_to_n?(a,n) num=a.find{|e| a.include?(n-e)} unless num puts "not exist" else p [n-num,num] end end a = [1,2,3,4,5] sum_to_n?(a,9) # >> [5, 4] sum_to_n?(a,11) # >> not exist逻辑
Enumerable#find 方法每次迭代传递一个数组元素。现在对于任何迭代,例如我有一个元素 e ,然后从n中减去它。现在我只是测试源数组中是否存在(ne),如果找到匹配项 #find 停止查找,并立即返回 e 。如果未找到,则进行下一次迭代。如果 #find 完成其迭代,但未找到(ne),根据文档,它将返回 nil 。
Enumerable#find method passing one array element per iteration.Now for any iteration,say I have an element e,and I subtracted it from n. Now I was just testing that (n-e) is present in the source array.If I found a match #find will stop finding,and immediately will return e.If not found,then it will go for next iteration. If #find completes its iteration,but didn't find (n-e),as per the documentation it will return nil.
更多推荐
查找给定数组中n是否为任意2个数字的和
发布评论