Last active
December 17, 2015 04:19
-
-
Save calebphillips/5549588 to your computer and use it in GitHub Desktop.
Mars Rover in Clojure Problem described here: http://battiguloncode.blogspot.com/2009/08/mars-rover-problem-from-thoughtworks.html
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
(require '[clojure.string :as str]) | |
(def turns | |
{:L {:N :W | |
:W :S | |
:S :E | |
:E :N} | |
:R {:N :E | |
:E :S | |
:S :W | |
:W :N}}) | |
(def move-deltas | |
{:N [0 1] | |
:W [-1 0] | |
:S [0 -1] | |
:E [1 0]}) | |
(defmulti exec-cmd (fn [_ c] c)) | |
(defmethod exec-cmd :M [m c] | |
(update-in m | |
[:position] | |
(partial map + (-> m :facing move-deltas)))) | |
(defmethod exec-cmd :default [m c] | |
(update-in m | |
[:facing] | |
(partial get (c turns)))) | |
(def rove (partial reduce exec-cmd)) | |
(defn parse-position [s] | |
(zipmap [:position :facing] | |
((juxt (comp (partial map #(Integer. %)) | |
(partial take 2)) | |
(comp keyword str last)) | |
(str/split s #" ")))) | |
(def parse-commands (partial map (comp keyword str))) | |
(defn parse-rover [[p c]] | |
[(parse-position p) (parse-commands c)]) | |
(defn input->rovers [rdr] | |
(->> rdr | |
(clojure.java.io/reader) | |
line-seq | |
(map str/trim) | |
rest | |
(partition 2) | |
(map parse-rover))) | |
(defn rover->str [r] | |
(->> (update-in r [:facing] name) | |
((juxt :position :facing)) | |
flatten | |
(str/join " "))) | |
(defn process-instructions [input] | |
(->> input | |
input->rovers | |
(map (partial apply rove)) | |
(map rover->str) | |
(str/join "\n"))) | |
(def input | |
"5 5 | |
1 2 N | |
LMLMLMLMM | |
3 3 E | |
MMRMMRMRRM") | |
(assert | |
(= (process-instructions (java.io.StringReader. input)) | |
"1 3 N\n5 1 E") ) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment