检查数组中两个不同数字的总和是否等于变量数?

在Ruby中,我想取一组数字,选择2个不同的数字,将这2个数字加在一起,看看那里的天气等于变量x的变量x。 这是我使用的代码

def arrayIsEqual? (numArray, x) return true if numArray.sample + numArray.sample == x return false if numArray.empty? || numArray.count == 1 end 

例如

 numArray = [4,2,7,5] x = 11 

arrayIsEqual (numArray, n)应返回true ,因为4 + 7 = n(11)

我如何让它工作?

我不希望它是2个随机数,只是任意2个不同的数字加起来n

看起来你正在试图查看数组中是否有任何两个数字加起来指定的值x 。 但是,您的代码只是随机选择两个数字并检查这些数字是否相加。

Ruby有Array#combination方法,它生成给定长度的所有组合:

 def contains_pair_for_sum?(arr, n) !!arr.uniq.combination(2).detect { |a, b| a + b == n } end 

有几点需要注意:

  • 首先,我们根据Ruby约定命名它:每个单词都是separated_by_underscores 。 的? 最后意味着该方法是谓词方法并返回true或false值。

  • 在方法内部,会发生一些事情。 让我们一块一块地看一下这条线。

    • arr :我们采用传入的数组。

    • <...>.uniq :我们只看独特元素(因为OP想要选择两个不同的数字)。

    • <...>.combination(2) :我们要求长度为2的数组的所有组合。如果数组是[4, 5, 6] ,我们得到[[4, 5], [4, 6], [5, 6]]

    • <...>.detect { |a, b| a + b == n } <...>.detect { |a, b| a + b == n } :我们寻找加起来为n的第一个组合。 如果我们找到了一个,那就是该方法的结果。 否则,我们nil

    • !!<...> :最后,我们从detect获取结果并将其否定两次。 第一个否定产生一个布尔值(如果我们得到的值是nil则为true如果是其他值则为false ); 第二个否定产生一个布尔值,该值与第一个否定的真值相同。 这是一个Ruby成语,可以将结果强制为truefalse

让我们看看它的实际效果:

 array = [4, 5, 9, 7, 8] contains_pair_for_sum?(array, 11) # => true (because [4, 7] sums to 11) contains_pair_for_sum?(array, 17) # => true (because [9, 8] sums to 17) contains_pair_for_sum?(array, 100) # => false (no pair matched) 

我知道你的问题是“我的数组中是否有任何一对数字等于x”,在这种情况下,这将满足您的需要:

 def has_pair_equal?(num_array, x) (0..num_array.length-1).any? do |i| num_array[i+1..-1].any? { |n| n + num_array[i] == x } end end 

这将检查数组中所有数字对的总和,并检查它们的总和是否为xsample从数组中随机选择一个项目,这意味着你的代码所做的是“如果我的数组中有一对数字等于x,则返回true”

 def array_is_equal? (num_array, x) equality = 0 num_array.each do |a| equality += 1 if a == x return true if equality == 2 end return false end 

在Ruby中使用小写和下划线表示变量。 这里的约定与其他语言不同。

一个class轮

 x=[4,2,7,5]; x.each_with_index.any? {|y,i| x.each_with_index.any? {|z,j| unless i==j; z+y==11; end } } 

并作为一个function

 def pair_sum_match?(arr, x) arr.each_with_index.any? do |y,i| arr.each_with_index.any? do |z,j| unless i==j z+y==x end end end end 

更新:添加each_with_index以避免在检查中包含自我。 现在好多了: – /

只需迭代一次,然后使用目标号码查看它是否匹配。 比这里的大部分答案快100倍

 numbers = ( -10..10 ).to_a numbers.unshift( numbers.first + -1 ) # if you do -20 or 20 numbers.push( numbers.last + 1 ) target = 5 searched = { } matches = { } numbers.each do |number| if searched[ target - number + 1 ] == true matches[ "#{ number }_plus_#{ target - number }" ] = target end searched[ number + 1 ] = true end ap matches