Skip to content

Instantly share code, notes, and snippets.

@sevvie
Last active December 17, 2015 19:59
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 sevvie/5664676 to your computer and use it in GitHub Desktop.
Save sevvie/5664676 to your computer and use it in GitHub Desktop.
I've fallen head-over-heels for Clojure. x.x Working through _Clojure Programming_, though, I've run into a problem I just can't seem to figure out; it behaves as if it's working, except it doesn't actually draw the maze. Forgive my spacious manner of writing Lisps. It just makes it easier to visualize everything for me.
(defn wilson-maze
"Returns a random maze carved out of walls; walls is a set of
two-item sets, #{a b}, where a and b are locations. The returned
maze is a set of the remaining walls."
[walls]
(let [paths (reduce
(fn [index [a b]] (merge-with into index {a [b] b [a]}))
{} (map seq walls))
start-loc (rand-nth (keys paths))]
(loop [walls walls
unvisited (disj (set (keys paths)) start-loc)]
(if-let [loc (when-let [s (seq unvisited)] (rand-nth s))]
(let [walk (iterate (comp rand-nth paths) loc)
steps (zipmap (take-while unvisited walk) (next walk))]
(recur (reduce disj walls (map set steps))
(reduce disj unvisited (keys steps))))
walls))))
(defn maze-grid [w h]
(set (concat
(for [i (range (dec w)) j (range h)] #{[i j] [(inc i) j]})
(for [i (range w) j (range (dec h))] #{[i j] [i (inc j)]}))))
(defn swing-draw [w h maze]
(doto (javax.swing.JFrame. "Maze")
(.setContentPane
(doto (proxy [javax.swing.JPanel] []
(paintComponent [^java.awt.Graphics g]
(let [g (doto ^java.awt.Graphics2D (.create g)
(.scale 10 10)
(.translate 1.5 1.5)
(.setStroke (java.awt.BasicStroke. 0.4)))]
(.drawRect g -1 -1 w h)
(doseq [[[xa ya] [xb yb]] (map sort maze)]
(let [[xc yc] (if (= xa xb)
[(dec xa) ya]
[xa (dec ya)])]
(.drawLine g xa ya xc yc))))))
(.setPreferredSize (java.awt.Dimension. (* 10 (inc w)) (* 10 (inc h))))))
.pack
(.setVisible true)))
(swing-draw 40 40 (wilson-maze (maze-grid 40 40)))
@sevvie
Copy link
Author

sevvie commented May 28, 2013

EDIT. I tucked in my parentheses for you all.

@sevvie
Copy link
Author

sevvie commented May 28, 2013

FIXED. I was a complete idiot and didn't let (wilson-maze) return anything to be (map sort)'ed.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment