Last active
December 31, 2015 08:09
-
-
Save pasviegas/7958679 to your computer and use it in GitHub Desktop.
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 marsrover.core | |
(:require [clojure.string :as s])) | |
(defn add-tuple [fst snd] | |
[(+ (first fst) (first snd)) (+ (second fst) (second snd))]) | |
(defn input->rovers [input] | |
(partition 2 (drop 1 (s/split-lines input)))) | |
(defn next-movement [facing] | |
({"E" [1 0] "W" [-1 0] "N" [0 1] "S" [0 -1]} facing)) | |
(defn rover-map [string] | |
(let [pos (s/split string #"\s")] | |
{:position [(read-string (first pos)) (read-string (second pos))] | |
:next (next-movement (last pos))})) | |
(defmulti move (fn [rover command] command)) | |
(defmethod move \M [rover command] | |
(assoc rover :position (add-tuple (:position rover) (:next rover)))) | |
(defmethod move \L [rover command] | |
(assoc rover :next [(- (second (:next rover))) (first (:next rover))])) | |
(defmethod move \R [rover command] | |
(assoc rover :next [(second (:next rover)) (- (first (:next rover)))])) | |
(defn main [input] | |
(map #(reduce move (rover-map (first %)) (second %)) (input->rovers input))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment