Skip to content

Instantly share code, notes, and snippets.

@axelarge
Last active August 17, 2017 08:32
Show Gist options
  • Save axelarge/e8801339c918e00c704994b181196563 to your computer and use it in GitHub Desktop.
Save axelarge/e8801339c918e00c704994b181196563 to your computer and use it in GitHub Desktop.
(ns aoc.day1
(:require [clojure.string :as str]))
(def test-input "R5, L5, R5, R3")
(def real-input (-> "src/aoc/day1.txt"
slurp
str/trim-newline))
(defn parse-step [step]
"Parses an individual step into a side/distance tuple.
e.g. \"R4\" -> [:R 4]"
(let [side (keyword (subs step 0 1))
distance (Integer/parseInt (subs step 1))]
[side distance]))
(defn parse-steps [steps]
"Turns an input string into a sequence of steps"
(map parse-step (str/split steps #", ")))
(defn turn [direction side]
"Applies a left or right turn to a direction to get the new direction"
(case [direction side]
([:N :L] [:S :R]) :W
([:N :R] [:S :L]) :E
([:E :L] [:W :R]) :N
([:E :R] [:W :L]) :S))
(defn move [[_ x y] direction distance]
"Moves from a position into a particular direction.
Returns the new position."
(case direction
:N [direction x (+ y distance)]
:S [direction x (- y distance)]
:E [direction (+ x distance) y]
:W [direction (- x distance) y]))
(defn apply-step
[[direction x y :as position] [side distance]]
"Applies a step (turn + move) to a position.
Returns the new position."
(let [new-direction (turn direction side)]
(move position new-direction distance)))
(defn travel [start steps]
"Applies a sequence of steps to a starting position and returns the end position"
(reduce apply-step start steps))
(defn distance [[_ x0 y0] [_ x1 y1]]
"Determines the Manhattan distance between two positions"
(+ (Math/abs (- x0 x1))
(Math/abs (- y0 y1))))
(defn trip-distance [steps]
"Determines the distance traveled for a sequence of steps"
(let [start [:N 0 0]]
(distance start (travel start steps))))
(defn solve
([steps-str] (trip-distance (parse-steps steps-str)))
([] (solve real-input)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment