Guest User

Untitled

a guest
Feb 19th, 2018
88
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.89 KB | None | 0 0
  1. #!/usr/bin/env ruby
  2. #
  3. # knapsack problem solution by backtracking.
  4. #
  5. # from:
  6. # Cプログラマのためのアルゴリズムとデータ構造
  7. # ISBN:4797304952
  8. # pp. 348
  9. #
  10. # author:
  11. # mootoh@gmail.com
  12. #
  13. require 'pp'
  14.  
  15. $stuffs = [ # [size, value]
  16. [2, 2],
  17. [3, 4],
  18. [5, 7],
  19. [7, 11],
  20. [9, 14]]
  21.  
  22. $values = {}
  23.  
  24. def knapsack_bt(m, stuffs, sofar)
  25. stuffs.each do |stuff|
  26. if stuff.first > m
  27. sum = 0
  28. sofar.each {|s| sum += $stuffs.find {|x| x.first == s}.last}
  29. $values[sofar.map {|so| $stuffs.map {|s| s.first}.index(so) }] = sum
  30. next
  31. end
  32. knapsack_bt(m - stuff.first, stuffs, sofar+[stuff.first])
  33. end
  34. end
  35.  
  36. def knapsack(m)
  37. stuffs = $stuffs.sort { |x, y| x.first <=> y.first }.reverse
  38. results = []
  39.  
  40. knapsack_bt(m, stuffs, [])
  41.  
  42. pp $values
  43.  
  44. print 'result: '
  45. pp $values.sort {|x,y| x[1] <=> y[1]}.last
  46. end
Add Comment
Please, Sign In to add comment