-1

我需要定位数组中的所有整数元素,其总和等于数组中的整数元素之一。

例如,假设我有一个这样的数组作为输入: [1, 2, 4, 10, 90, 302, 312, 500]

然后输出应该包含所有整数元素,包括作为其他元素之和的整数元素。它会像:[10, 302, 312]10+302 = 312

这是我在 ruby​​ 中尝试过的:

numbers = [1, 2, 4, 10, 90, 302, 312, 500]
numbers.each_with_index do |number, index|
  target = []
  return [] if numbers.size < 3
  target << number
  puts "target in numbers.each: #{target.inspect}"
  0.upto(numbers.size).each do |i|
    puts "target in (index+1).upto: #{target.inspect}"
    target << numbers[i] unless index == i
    next if target.size < 2
    break if target.inject(&:+) > numbers.max
    puts "== array starts =="
    puts [target, target.inject(&:+)].flatten.inspect if numbers.include? target.inject(&:+)
    puts "== array ends =="
  end
end

但它没有产生预期的输出。如果我对此有任何运气,我会更新。在那之前,谁能指出我在这里做错了什么?谢谢。

算法对我也有好处。

4

2 回答 2

1

一个实现:

arr = [1, 2, 4, 10, 90, 302, 312, 500]

(2..arr.count).each do |len|
  arr.combination(len).each do |comb|
    sum = comb.inject(:+)
    if arr.include? sum
      puts (comb << sum).inspect
    end
  end
end
于 2013-09-19T08:36:18.007 回答
1

zwippie 的小改动的答案..

arr = [1, 2, 4, 10, 90, 302, 312, 500]
result = []
(2..arr.count-1).to_a.each do |len|
  arr.combination(len).to_a.each do |comb|
    sum = comb.inject(:+)
    if arr.include? sum
      result << (comb << sum)
    end
  end
end
result
于 2013-09-19T09:10:12.803 回答