Skip to content

Instantly share code, notes, and snippets.

@suryart
Created November 20, 2013 18:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save suryart/7568177 to your computer and use it in GitHub Desktop.
Save suryart/7568177 to your computer and use it in GitHub Desktop.
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,…
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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment