Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on May 24th, 2012  |  syntax: None  |  size: 1.68 KB  |  hits: 10  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. class State
  2.   attr_accessor :value, :parent, :cost, :distance
  3.   def initialize(value, distance, parent)
  4.     @value, @distance, @parent, @cost = value, distance, parent, 0
  5.   end
  6.   def to_s; value; end
  7. end
  8.  
  9. def search(strategy, current, final)
  10.   return false if current.nil?
  11.   return true  if current.value == final
  12.  
  13.   strategy.produce(current)
  14.   search(strategy, strategy.choice, final)
  15. end
  16.  
  17. # Best-first
  18. class BestFirstStrategy < Array
  19.   attr_reader :visited
  20.   def initialize(state_space)
  21.     @state_space = state_space
  22.     @visited     = []
  23.   end
  24.  
  25.   def produce(state)
  26.     @state_space.each do |current_state|
  27.       if current_state.parent == state.value
  28.         current_state.cost = current_state.distance + state.cost
  29.         push(current_state)
  30.       end
  31.     end
  32.   end
  33.  
  34.   def choice
  35.     node = min_by{ |n| n.cost };
  36.     delete_if{ |n| n.value == node.value }
  37.     @visited.push(node) unless node.nil?
  38.     node
  39.   end
  40. end
  41.  
  42. # state space
  43. ss = []
  44. ss << State.new(:arad,          0,  nil)
  45. ss << State.new(:zerind,       75,  :arad)
  46. ss << State.new(:timisoara,   118,  :arad)
  47. ss << State.new(:sibiu,       140,  :arad)
  48. ss << State.new(:oradea,       71,  :zerind)
  49. ss << State.new(:sibiu,       151,  :oradea)
  50. ss << State.new(:fagaras,      99,  :sibiu)
  51. ss << State.new(:rimnicu,      80,  :sibiu)
  52. ss << State.new(:bucharest,   211,  :fagaras)
  53. ss << State.new(:pitesti,      97,  :rimnicu)
  54.  
  55. def find_parent(ss, value)
  56.   ss.select do |s|
  57.     s.value == value
  58.   end.first
  59. end
  60.  
  61. strategy = BestFirstStrategy.new(ss)
  62. puts "Found? #{search(strategy, ss.first, :bucharest)}"
  63.  
  64. goal = strategy.visited.select{ |s| s.value == :bucharest }.first
  65. puts goal
  66. s = goal
  67. while s != nil
  68.   p s.value
  69.   s = find_parent(ss, s.parent)
  70. end