Advertisement
Guest User

Untitled

a guest
May 27th, 2016
57
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.99 KB | None | 0 0
  1. // State : a protocole for states in the search space
  2. protocol State : Equatable {
  3.  
  4. // successors() : returns an array of successors states in the search space
  5. func successors() -> [Successor<Self>]
  6.  
  7. // heuristic(goal) : returns the heuristic value for a given states in relation to a given goal state
  8. func heuristic(goal:Self) -> Double
  9.  
  10. // id : a string identifying a state
  11. var id : String { get }
  12.  
  13. }
  14.  
  15. // States are compared by their id
  16. func ==<T:State>(lhs:T, rhs:T) -> Bool {
  17. return lhs.id==rhs.id
  18. }
  19.  
  20. // Successor : represents a successor state and its cost
  21. struct Successor<T:State> {
  22. var state: T
  23. var cost: Double
  24. }
  25.  
  26. // Plan : a plan of states
  27. struct Plan<T:State> {
  28.  
  29. // states : an array of states that make a plan
  30. var states: [T]
  31.  
  32. // cost : the total cost of the plan
  33. var cost: Double
  34.  
  35. // isNot(another) : checks if another plan is different from the current one
  36. func isNot(another: Plan) -> Bool {
  37. return !(states == another.states && cost == another.cost)
  38. }
  39.  
  40. }
  41.  
  42. // AStar<TState> : finds the A* solution (nil if no solution found) given a start state and goal state
  43. func AStar<TState:State>(start: TState, goal: TState) -> Plan<TState>? {
  44.  
  45. var fringe : [Plan<TState>] = [Plan(states: [start], cost: 0)]
  46.  
  47. while fringe.count>0 {
  48.  
  49. let bestPlan = fringe.minElement({
  50. a,b
  51. in
  52. a.cost + a.states.last!.heuristic(goal) < b.cost + b.states.last!.heuristic(goal)
  53. })!
  54.  
  55. fringe = fringe.filter({
  56. plan in plan.isNot(bestPlan)
  57. })
  58.  
  59. if bestPlan.states.last! == goal {
  60. return bestPlan
  61. }else{
  62. let successors = bestPlan.states.last!.successors()
  63. for successor in successors.filter({ s in !bestPlan.states.contains(s.state) }) {
  64. let newPlan = Plan(states: bestPlan.states+[successor.state], cost: bestPlan.cost+successor.cost)
  65. fringe.append(newPlan)
  66. }
  67. }
  68.  
  69. }
  70.  
  71. return nil
  72.  
  73. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement