Skip to content

Instantly share code, notes, and snippets.

@denlab
Created April 10, 2012 08:15
Show Gist options
  • Save denlab/2349290 to your computer and use it in GitHub Desktop.
Save denlab/2349290 to your computer and use it in GitHub Desktop.
hands on clj
(ns ^{:doc "Find one path in a labyrinth"}
hands-on-march-2012.laby
(:use [midje.sweet]
[clojure
[pprint :only [pprint]]
[repl :only [doc]]]))
(unfinished )
;; ------------- rules of the game ------------------
;;
;; - '*' are walls
;; - everything else are empty
;; - the labyrinth is surrounded by walls
;; - labyrinth is always square
;;
;; --------------------------------------------------
(def laby-ex
'[[* . .]
[* . *]
[* . .]])
(defn wall?
[l yx] (or (some #(or (< % 0) (<= (count l) % )) yx)
(= '* (get-in l yx))))
(fact "wall?"
(wall? '[[. .]
[. *]] [0 0]) => falsey
(wall? '[[. .]
[. *]] [0 1]) => falsey
(wall? '[[. .]
[. *]] [1 0]) => falsey
(wall? '[[. .]
[. *]] [1 1]) => truthy)
(fact "wall? outside the square"
(wall? '[[.]] [0 -1]) => truthy
(wall? '[[.]] [0 1]) => truthy
(wall? '[[.]] [-1 0]) => truthy
(wall? '[[.]] [ 1 0]) => truthy
(wall? '[[.]] [0 0]) => falsey)
(defn neighboors-raw
[l [y x]] {'u [(dec y) x], 'd [(inc y) x],
'r [y (inc x)], 'l [y (dec x)]})
(fact "neighboors-raw"
(neighboors-raw '[[. . .]
[. . .]
[. . .]] [1 1]) => {'d [2 1], 'u [0 1], 'r [1 2], 'l [1 0]}
(neighboors-raw '[[. . .]
[. . .]
[. . .]] [0 0]) => {'d [1 0], 'u [-1 0], 'r [0 1], 'l [0 -1]})
(defn neighboors "The possible neighboors: Those who aren't walls"
[l yx] (into {}
(remove #(wall? l (second %))
(neighboors-raw l yx))))
(fact "neighboors"
(neighboors '[[. *]
[. .]] [0 0]) => {'d [1 0]})
(defn add-wall
[l yx] (assoc-in l yx '*))
(fact "add-wall"
(add-wall '[[.]] [0 0]) => '[[*]])
(defn dead?
[l yx] (empty? (filter #(not (wall? l %))
(vals (neighboors-raw l yx)))))
(fact "dead?"
(dead? '[[. *]
[* *]] [0 0]) => truthy
(dead? '[[. *]
[. *]] [0 0]) => falsey)
(defn solve
[l a b]
(cond (= a b) []
(dead? l a) [:dead]
:else (first (remove #(= (last %) :dead)
(map (fn [[k v]] (concat [k] (solve (add-wall l a) v b)))
(neighboors l a))))))
(fact "solve"
(solve '[[a .]
[b .]] [0 0] [1 0]) => '[d])
(fact "solve"
(solve '[[c .]
[. .]] [0 0] [0 0]) => [])
(fact "solve"
(solve '[[a *]
[* b]] [0 0] [0 1]) => [:dead])
(fact "solve"
(solve '[[a b]
[* *]] [0 0] [0 1]) => '[r])
(fact "solve"
(solve '[[a *]
[b *]] [0 0] [1 0]) => '[d])
(fact "solve"
(solve '[[a . .]
[. * .]
[. . b]] [0 0] [2 2]) => '[d d r r])
(fact "solve"
(solve '[[a . .]
[. * .]
[* . b]] [0 0] [2 2]) => '[r r d d])
(fact "solve"
(solve '[[a . . .]
[. * * .]
[. . * *]
[* . . b]] [0 0] [3 3]) => '[d d r d r r])
(fact "solve"
(solve '[[a . . . .]
[. * * * .]
[* . . . .]
[* . * * *]
[* . . . b]] [0 0] [3 3]) => '(r r r r d d l l l d d r r))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment