Created
December 7, 2012 15:25
-
-
Save jordanlewis/4233931 to your computer and use it in GitHub Desktop.
8-puzzle
This file contains hidden or 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
(ns playground.eightpuz) | |
(defn correct [b] (= b [1 2 3 8 0 4 7 6 5])) | |
(def dirs {'l -1 'r 1 'u -3 'd 3}) | |
(defn move [b dir] | |
(let [idx (.indexOf b 0) | |
col (mod idx 3) | |
tgt (+ idx (dirs dir))] | |
(if | |
(or (and (= 'l dir) (= 0 col)) | |
(and (= 'r dir) (= 2 col)) | |
(and (= 'u dir) (> 3 idx)) | |
(and (= 'd dir) (< 5 idx))) | |
nil | |
(assoc (assoc b idx (b tgt)) tgt 0)))) | |
(defn solve [boardstack moves] | |
(let [cur (first boardstack)] | |
(cond (correct cur) moves | |
(some #{cur} (rest boardstack)) nil | |
:else (first (filter identity (map #(solve (cons boardstack (move cur %)) (conj moves %)) | |
(keys dirs))))))) | |
(keys dirs) | |
(correct (move [1 2 3 0 8 4 7 6 5] 'r)) | |
;(solve (list [1 2 3 0 8 4 7 6 5]) []) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment