Guest User

Untitled

a guest
Jul 20th, 2018
70
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.64 KB | None | 0 0
  1. #!/usr/bin/env ruby
  2.  
  3. class SubsetSum
  4. attr_accessor :nearest
  5.  
  6. def initialize(items, target)
  7. @nearest = 0
  8. for combination_dec in 1..(2**items.size - 1)
  9. subset_sum = 0
  10. combination_bin = combination_dec.to_s(base=2).rjust(items.size, "0")
  11. for digit in 0..items.size - 1
  12. subset_sum += items[digit] if combination_bin[digit, 1].eql? "1"
  13. end
  14. @nearest = subset_sum if (target - subset_sum) < (target - nearest)
  15. end
  16. end
  17. end
  18.  
  19. subset_sum = SubsetSum.new(
  20. [ 309, 122, 212, 151, 245, 107, 180, 174, 142, 244, 439, 278, 106, 286, 183, 136, 184, 188, 123 ],
  21. 2165
  22. )
  23.  
  24. puts subset_sum.nearest
Add Comment
Please, Sign In to add comment