Skip to content

Instantly share code, notes, and snippets.

@pasviegas
Last active December 31, 2015 08:09
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 pasviegas/7958679 to your computer and use it in GitHub Desktop.
Save pasviegas/7958679 to your computer and use it in GitHub Desktop.
(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