Guest User

Untitled

a guest
Jun 19th, 2018
87
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.30 KB | None | 0 0
  1. #!/bin/ruby
  2.  
  3. class Item
  4. include Comparable
  5. attr_accessor :value, :route
  6.  
  7. def initialize v
  8. @value = v
  9. @route = []
  10. end
  11.  
  12. def +(other)
  13. @value += other.value
  14. @route << other.value
  15. self
  16. end
  17.  
  18. def <=>(other)
  19. @value == other.value ? 0 :
  20. @value > other.value ? 1 :
  21. -1
  22. end
  23. end
  24.  
  25. class Cache
  26. def initialize
  27. @cache = {}
  28. end
  29. def _key x, y
  30. x.to_s + '_' + y.to_s
  31. end
  32. def [](x, y)
  33. @cache[_key x, y]
  34. end
  35. def []=(x, y, r)
  36. r_new = Item.new r.value
  37. r_new.route = r.route.dup
  38. @cache[_key x, y] = r_new
  39. end
  40. def has_key? x, y
  41. @cache.has_key? _key x, y
  42. end
  43. def size
  44. @cache.size
  45. end
  46. def values
  47. @cache.values
  48. end
  49. end
  50.  
  51. def f xs, i, size
  52. if @cache.has_key? i, size
  53. @cache[i, size]
  54. elsif i == xs.length
  55. Item.new 0
  56. elsif size < 0
  57. r = f(xs, i + 1, size)
  58. @cache[i, size] = r
  59. r
  60. else
  61. x = xs[i]
  62.  
  63. r1 = f(xs, i + 1, size)
  64. r2 = f(xs, i + 1, size - 1) + x
  65.  
  66. r = (r1 > r2) ? r1 : r2
  67. @cache[i, size] = r
  68. r
  69. end
  70. end
  71.  
  72. items = (1..100).map{|x| Item.new x * 900}
  73. @cache = Cache.new
  74. p f items, 0, 100
  75. p @cache.values.to_a.select{|x| x.value <= 1000000}.sort{|x,y| -(x.value <=> y.value)}.first
Add Comment
Please, Sign In to add comment