Skip to content

Instantly share code, notes, and snippets.

@ToxicFrog
Created July 30, 2013 14:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ToxicFrog/8f4ca169fd12c3e08e2f to your computer and use it in GitHub Desktop.
Save ToxicFrog/8f4ca169fd12c3e08e2f to your computer and use it in GitHub Desktop.
(def board ">>> <<<") ; starting board
(def goal "<<< >>>") ; target board
; the set of valid moves
(def moves {
"> " " >"
" <" "< "
">< " " <>"
" ><" "<> "
})
(defn print-history [state]
(println "=======")
(dorun (map println state)))
(defn as-str [seq] (apply str seq))
(defn check-move [i move]
(if-let [result (moves (as-str move))]
[i result]
nil))
(defn find-moves [board]
(concat
(keep-indexed check-move (partition 2 1 board))
(keep-indexed check-move (partition 3 1 board))))
(defn splice-seq [xs n splice]
(let [head (take n xs)
tail (drop (+ n (count splice)) xs)]
(concat head splice tail)))
(defn splice-move [state [n move]]
(conj state
(as-str (splice-seq (first state) n move))))
(defn next-states [state]
(let [moves (find-moves (first state))]
(map (partial splice-move state) moves)))
(defn solve-jumping-pegs [states]
(let [finished (filter #(= goal (first %)) states)]
(cond
(not-empty finished) finished
:else (recur (mapcat next-states states)))))
(dorun (map print-history
(solve-jumping-pegs [(list board)])))
(println "=======")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment