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]