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

时间:2017-01-17 19:19:03

标签: 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 + y == sum}
end    

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

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

2 个答案:

答案 0 :(得分:0)

考虑到评论中的约束:它们不必相邻。关注的索引号I是该对中的第二个数字。它必须是最低的。

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

答案 1 :(得分:0)

array_ints = [10,5,2,3,7,5,8,2] sum = 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]