Advertisement
Guest User

Untitled

a guest
Jun 25th, 2019
88
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.99 KB | None | 0 0
  1. bool Astar::new_search( SearchState& start,
  2. SearchState& goal,
  3. std::vector<SearchState>& solution){
  4.  
  5. double weight=1.0;
  6.  
  7. if(start==goal) //calls GridNode's (derived) implementation
  8. std::cout<<" ";
  9.  
  10. //initialize costs
  11. //(...)
  12. PriorityQueue<SearchState, double> frontier;
  13. frontier.put(start, 0);
  14.  
  15. came_from[start] = start;
  16. cost_so_far[start] = 0;
  17.  
  18. size_t expandedStates=0;
  19. while (!frontier.empty()) {
  20.  
  21.  
  22. SearchState current = frontier.get();
  23.  
  24. if (current == goal) {//calls SearchState's(base) implementation
  25. goal.setGCost(current.getGCost());
  26. break;
  27. }
  28.  
  29. std::vector<SearchState> exploredStates = explorer->neighbors(current);
  30. for (SearchState next : exploredStates) {
  31.  
  32. double new_cost = next.getGCost();
  33. if (cost_so_far.find(next) == cost_so_far.end()//if not in cost_so_far
  34. || new_cost < cost_so_far[next]) {
  35. cost_so_far[next] = new_cost;
  36. double priority = new_cost + weight*(next.getHCost());
  37. frontier.put(next, priority);
  38. came_from[next] = current;
  39. }
  40. }
  41. expandedStates++;
  42. }
  43. solution = reconstruct_path(start, goal, came_from);
  44. printSolutionStates(solution);
  45. std::cout<<"Expanded States: "<<expandedStates<<std::endl;
  46. std::cout<<"Number of States in Solutiion: "<<solution.size()<<std::endl;
  47. std::cout<<"Effeciency: "<<(double)solution.size()/expandedStates<<std::endl;
  48. return true;
  49. }
  50.  
  51. template<typename T, typename priority_t>
  52. struct PriorityQueue {
  53. typedef std::pair<priority_t, T> PQElement;
  54. std::priority_queue<PQElement, std::vector<PQElement>,
  55. std::greater<PQElement>> elements;
  56.  
  57. inline bool empty() const {
  58. return elements.empty();
  59. }
  60.  
  61. inline void put(T item, priority_t priority) {
  62. elements.emplace(priority, item);
  63. }
  64.  
  65. T get() {
  66. T best_item = elements.top().second;
  67. elements.pop();
  68. return best_item;
  69. }
  70. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement