查找给定数组中n是否为任意2个数字的和

编程入门 行业动态 更新时间:2024-10-27 00:24:16
本文介绍了查找给定数组中n是否为任意2个数字的和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在尝试查找 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个数字的和

本文发布于:2023-11-30 10:10:47,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1649611.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:定数   组中   数字

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!