2017-01-17 46 views
0

我需要查找给定数组中的第一个组合,并将它们加起来成为特定值。组合需要作为一个整体的最低索引组合。如何找到添加到特定值的子阵列的所有组合

我大部分的问题制定出:

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. 

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

+0

是单项目排除?是否允许两个以上的项目?邻接关系如同你的3,7例子吗? – coreyward

+0

排除单个项目。超过两个项目是不允许的。他们不必相邻。我关心的指数是这对货币中的第二个数字。它需要是最低的。 –

回答

0

考虑到从评论中的约束:他们不必是相邻的。我关心的指数是这对货币中的第二个数字。它需要是最低的。

def pairs(array_ints, sum) 
    array_ints.combination(2).inject({}) do |acc, pair| 
    first, second = pair 

    # 
    # Find the last occurrence of the second element. Note the use of 
    # 'rindex' to search from the end of the array. The same element 
    # may occur more than once ... 
    # 
    index = array_ints.rindex(second) 

    if first + second == sum 
     if !acc[:index] || acc[:index] > index 
     # Store the first match, or replace it if the stored 
     # index is higher than the current index 
     acc[:result] = pair 
     acc[:index] = index 
     end 
    end 

    acc 
    end.fetch(:result, []) 
end 

describe "pairs" do 
    let(:array) { [10, 5, 2, 3, 7, 5] } 

    describe "when there are multiple combinations that add up to the sum" do 
    it "finds the pair having the lowest index of the second element in the pair" do 
     expect(pairs(array, 10)).to eq([3,7]) 
     expect(pairs(array, 8)).to eq([5,3]) 
    end 
    end 

    describe "when there is no combination matching the sum" do 
    it "returns an empty array" do 
     expect(pairs(array, 1)).to eq([]) 
    end 
    end 

end 
0

array_ints = [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] 
相关问题