Search code examples
rubyarraysruby-on-rails-3algorithmruby-on-rails-3.1

Finding all elements(which are integer) in an array whose sum is equals to the element exists within the array


I need to locate all integer elements in an array, whose sum is equal to one of the integer elements within the array.

For example, let's assume I have an array like this as input: [1, 2, 4, 10, 90, 302, 312, 500]

Then output should have all integer elements including the integer element which is sum of other elements. It will be like: [10, 302, 312] i.e. 10+302 = 312

This is what I tried in 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

But it's not making expected output. I'll update if I get any luck on this. Till then can anyone point out that what I am doing wrong here? Thanks.

An algorithm will be good for me as well.


Solution

  • An implementation:

    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