Skip to content

Instantly share code, notes, and snippets.

@alesya-h
Created February 3, 2017 13:42
Show Gist options
  • Save alesya-h/c7ef3d628f989fec5aefe4d3e833cf92 to your computer and use it in GitHub Desktop.
Save alesya-h/c7ef3d628f989fec5aefe4d3e833cf92 to your computer and use it in GitHub Desktop.
(ns adventure-of-code.task1
(:require [clojure.string :as str]))
(defn new-direction [old-direction offset]
(-> old-direction
(+ offset)
(mod 4)))
(defn rotation-to-direction-offset [rotation-str]
(case rotation-str
"L" -1
"R" 1))
(defn parse-step [step] ;; "L123" -> [-1 123]
(let [rotation-str (.substring step 0 1)
step-count-str (.substring step 1)]
[(rotation-to-direction-offset rotation-str) (Integer. step-count-str)]))
(def initial-state
[0 ;; first direction. let's say it's up, but it doesn't matter.
[0 0 0 0]]) ;; steps in each of 4 directions. see compute-distance-from-steps
(defn step [[old-direction steps-in-directions] step] ;-> [current-direction steps-in-directions]
(let [[direction-offset step-count] (parse-step step)
current-direction (new-direction old-direction direction-offset)]
[current-direction (update steps-in-directions current-direction + step-count)]))
(defn compute-distance-from-steps [[up right down left]]
(+ (Math/abs (- up down))
(Math/abs (- left right))))
(defn compute [input]
(->> (str/split input #", ")
(reduce step initial-state)
last
compute-distance-from-steps))
(print (compute "L6, R3, L42, R13, R12"))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment