Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/22.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby 如何查找添加到特定值的所有子阵列组合_Ruby - Fatal编程技术网

Ruby 如何查找添加到特定值的所有子阵列组合

Ruby 如何查找添加到特定值的所有子阵列组合,ruby,Ruby,我需要找到给定数组中的第一个组合,它加起来就是一个特定的值。该组合必须是整体索引最低的组合 我已经解决了大部分问题: def pairs(array_ints, sum) array_ints.combination(2).detect {|x, y| x + y == sum} end 此方法不提供具有最低索引对的组合。例如: def pairs([10, 5, 2, 3, 7, 5], 10) array_ints.combination(2).detect {|x, y| x +

我需要找到给定数组中的第一个组合,它加起来就是一个特定的值。该组合必须是整体索引最低的组合

我已经解决了大部分问题:

def pairs(array_ints, sum)
  array_ints.combination(2).detect {|x, y| x + y == sum}
end
此方法不提供具有最低索引对的组合。例如:

def pairs([10, 5, 2, 3, 7, 5], 10)
  array_ints.combination(2).detect {|x, y| x + y == sum}
end    

#output [5, 5]
#desired output [3, 7] because they appear earlier as a pair in the array. 

如何输出等于特定和的所有对,并选择索引最低的对

考虑到您的评论限制:它们不必相邻。我关心的索引号是这对中的第二个数字。它必须是最低的


数组\u int=[10,5,2,3,7,5,8,2]总和=10

def pairs(array_ints, sum)
 arr = []
 array_ints.each_cons(2){|x,y| arr.push(x,y) if x+y==sum }
 print arr.first(2)
end

# output [3, 7]

是否排除单个项目?允许两个以上的项目吗?相邻关系是否重要,如您的3,7示例中所示?不包括单个项目。不允许超过两项。它们不必相邻。我关心的索引号是这对中的第二个数字。它必须是最低的。
def pairs(array_ints, sum)
 arr = []
 array_ints.each_cons(2){|x,y| arr.push(x,y) if x+y==sum }
 print arr.first(2)
end

# output [3, 7]