Created
January 30, 2014 17:12
-
-
Save bzar/8713648 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(defn a-star [get-options calc-distance from to] | |
(let [add-node (fn [queue node] | |
(if (> (calc-distance (:pos (first queue)) to) (calc-distance (:pos node) to)) | |
(cons node queue) | |
(cons (first queue) (add-node (rest queue) node)))) | |
process (fn [[node & queue] visited] | |
(if (= (:pos node) to) node | |
(if (and (get visited (:pos node)) (< (:cost (get visited (:pos node))) (:cost node))) | |
(process queue visited) | |
(let [new-nodes (for [new-pos (get-options (:pos node))] | |
{:pos new-pos :cost (inc (:cost node)) :from node}) | |
new-queue (reduce add-node queue new-nodes) | |
new-visited (assoc visited (:pos node) node)] | |
(if (nil? new-nodes) nil (process new-queue new-visited)))))) | |
extract-path (fn [node path] | |
(if (nil? node) path | |
(extract-path (:from node) (cons (:pos node) path))))] | |
(extract-path (process '({:pos from :cost 0 :from nil}) {}) nil))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment