Class: ActiveBacon::A::Star
- Inherits:
-
Object
- Object
- ActiveBacon::A::Star
- Defined in:
- lib/active_bacon/a/star.rb
Defined Under Namespace
Classes: PriorityQueue
Instance Method Summary collapse
- #find_path(start, goal) ⇒ Object
-
#initialize(adjacency_func, cost_func) ⇒ Star
constructor
A new instance of Star.
Constructor Details
#initialize(adjacency_func, cost_func) ⇒ Star
Returns a new instance of Star.
13 14 15 16 17 18 |
# File 'lib/active_bacon/a/star.rb', line 13 def initialize(adjacency_func, cost_func) @adjacency = adjacency_func @cost = cost_func # no use for distance function yet # @distance = distance_func end |
Instance Method Details
#find_path(start, goal) ⇒ Object
20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 |
# File 'lib/active_bacon/a/star.rb', line 20 def find_path(start, goal) result = Hashie::Mash.new(:success? => false) visited = {} pqueue = PriorityQueue.new pqueue << [1, [start,[], 0]] until result.success? || pqueue.empty? # e.g. start, [], 0 spot, path_so_far, cost_so_far = pqueue.next # if already been there, then skip next if visited[spot] # [] + start new_path = path_so_far + [spot] # if goal == spot, return the result if goal == spot result.path = new_path result[:success?] = true result[:cost] = cost_so_far else # continue visited[spot] = cost_so_far @adjacency.call(spot).each do |new_spot| # if already been there, skip it next if visited[new_spot] this_cost = @cost.call(spot, new_spot) if this_cost new_cost = cost_so_far + this_cost # add to queue pqueue << [ new_cost, [new_spot, new_path, new_cost]] end end end end # while result[:visited] = visited return result # success? is false end |