2019/utils/search.rb
#! A* search from start to goal
A* search from start to goal
A * search from start to goal
def astar(start, neighbours:, heuristic:, goal:)
    g_score = Hash.new(1.0 / 0.0)
    g_score[start] = 0
    closed = {}
    open = PriorityQueue.new
    open[start] = heuristic[start]
    prev = {}
    while (current = open.pop)
      closed[current] = true
      return [g_score[current], path_of(prev, current)] if goal[current]
      neighbours[current].each { |neighbour, cost|
        next if closed[neighbour]
        tentative_g_score = g_score[current] + cost
        next if tentative_g_score >= g_score[neighbour]
        prev[neighbour] = current
        g_score[neighbour] = tentative_g_score
        open[neighbour] = tentative_g_score + heuristic[neighbour]
      }
    end
    nil
  end
def astar ( start , neighbours : , heuristic : , goal : ) g_score = Hash . new ( 1.0 / 0.0 ) g_score [ start ] = 0 closed = { } open = PriorityQueue . new open [ start ] = heuristic [ start ] prev = { } while ( current = open . pop ) closed [ current ] = true return [ g_score [ current ] , path_of ( prev , current ) ] if goal [ current ] neighbours [ current ] . each { | neighbour , cost | next if closed [ neighbour ] tentative_g_score = g_score [ current ] + cost next if tentative_g_score >= g_score [ neighbour ] prev [ neighbour ] = current g_score [ neighbour ] = tentative_g_score open [ neighbour ] = tentative_g_score + heuristic [ neighbour ] } end nil end
A* search from start to goal
A * search from start to goal
start
neighbours
heuristic
goal