Created
November 9, 2013 21:15
-
-
Save kitallis/7390133 to your computer and use it in GitHub Desktop.
neena and kitallis delve into clj
This file contains 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 mars-rover.core) | |
; | |
; first: grid size | |
; | |
; rest: pairs of 2 lines each, containing rover agenda. | |
; 1st line for pair: | |
; rover starting position on the grid | |
; 2nd line for pair: | |
; all instructions to move | |
; | |
; X Y D | |
; L => D | |
; defn move (for L) | |
; | |
; W => X -> X - 1 | |
; N => Y -> Y + 1 | |
; E => X -> X + 1 | |
; S => Y -> Y - 1 | |
(def directions ('W 'N 'E 'S)) | |
(def direction-weights {'W -1 'E +1 'N +1 'S -1}) | |
(def new-direction [position direction] | |
(conj (pop position) (nth directions (mod (+ direction (indexOf (last position))) 4)))) | |
(def one-direction [position] | |
(let [coord (mod (indexOf direction (last position)) 2)] | |
(assoc position coord (+ (get direction-weights (last position)) (nth position coord))))) | |
(defn move [position instructions] | |
(if (empty instructions) | |
position | |
(let [new_position (case (first instructions) | |
"L" (new-direction position -1) | |
"R" (new-direction position +1) | |
"M" (one-direction position) | |
)] | |
(move new_position (rest instructions))))) | |
(defn parse [rover-agenda] | |
((map read-string (clojure.string/split (first rover-agenda) #" ")) (clojure.string/split (second rover-agenda) #" "))) | |
(defn display-rover [position] | |
(apply println position)) | |
(defn -main | |
[] | |
(let [grid (read-line)] | |
(map (fn [ra] (apply println (parse ra))) (partition 2 (take-while (comp not nil?) (repeatedly read-line)))) | |
;(map (comp display-rover (partial apply move) parse) (partition 2 (take-while (comp not nil?) (repeatedly read-line)))) | |
)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
/@deobald