2017-01-17 5 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

は除外単一アイテムですか? 2つ以上のアイテムは許可されていますか?あなたの3、7の例のように、隣接関係は重要ですか? – coreyward

+0

単一項目は除外されます。 2つ以上の項目は許可されていません。それらは隣接する必要はありません。私が心配しているインデックス番号は、ペアの2番目の数字です。それは最も低いものである必要があります。 –

答えて

0

コメントからの制約を考慮に入れてください:それらは隣接する必要はありません。私が心配しているインデックス番号は、ペアの2番目の数字です。それは最も低いものである必要があります。

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] 
関連する問題