Skip to content

Instantly share code, notes, and snippets.

@trobrock
Created November 5, 2011 22:31
Show Gist options
  • Save trobrock/1342120 to your computer and use it in GitHub Desktop.
Save trobrock/1342120 to your computer and use it in GitHub Desktop.
numbers = [1,2,3,4,5,6,7,8,9]
target = 50
k = 5
def calculate_sum(inputs, k)
inputs.each_index do |i|
pairing = [inputs[i]]
inputs.each_index do |j|
next if i == j
if pairing.size == k
yield pairing
pairing = [inputs[i]]
end
pairing << inputs[j]
end
end
end
calculate_sum(numbers, k) do |set|
if set.inject(&:+) == target
puts set.inspect
exit
end
end
puts "No combination exists"
exit 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment