Guest User

Untitled

a guest
Apr 20th, 2018
73
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.70 KB | None | 0 0
  1. #
  2. # Google interview question: find all combinations that sum up to a value
  3. #
  4. require 'set'
  5.  
  6. def summables(vector, remainder, so_far, answers)
  7. answers.add(so_far) if remainder == 0
  8.  
  9. car = vector[0]
  10. return answers if car == nil
  11.  
  12. cdr = vector[1..-1]
  13.  
  14. summables(cdr, remainder - car, so_far + [car], answers) if car <= remainder && car > 0 #summables including car where no soln yet
  15. summables(cdr, remainder, so_far, answers) #all summables excluding car
  16. end
  17.  
  18. def find_summables(vector, sum)
  19. summables(vector, sum, [], Set.new).to_a
  20. end
  21.  
  22.  
  23. print(find_summables([1, 2, 3, 5, 7, 2], 7))
  24. print("\n----\n")
  25.  
  26. print(find_summables([1,4,3,3,6,8,8,8,8,8,8,8,8,7,5,5,45,6,7,8,8,7,7,1,6,5,2], 13))
  27. print("\n----\n")
Add Comment
Please, Sign In to add comment