Advertisement
luorduz

advent-22-09

Dec 11th, 2022
495
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Clojure 1.32 KB | Source Code | 0 0
  1. (defn follow [[hx hy] [tx ty]] (let [change {false dec, true inc}] (
  2.   cond
  3.     (every? #{-1 0 1} [(- hx tx) (- hy ty)]) [tx ty]
  4.     (zero? (- hx tx)) [tx ((change (> hy ty)) ty)]
  5.     (zero? (- hy ty)) [((change (> hx tx)) tx) ty]
  6.     :else [((change (> hx tx)) tx) ((change (> hy ty)) ty)]
  7. )))
  8.  
  9. (defn make-step [dir head tail] (let [
  10.   transforms {"R" [inc identity], "U" [identity inc], "D" [identity dec], "L" [dec identity]}
  11.   transform (transforms dir)
  12.   new-head (vec (map #(%1 %2) transform head))
  13. ] [new-head (follow new-head tail)]))
  14.  
  15. (defn travel [[history knots] [dir steps]] (reduce
  16.   (fn [[history knots] _] (let [
  17.     [head sec] (make-step dir (first knots) (second knots))
  18.     new-knots (reduce #(conj %1 (follow (peek %1) %2)) [sec] (nthrest knots 2))
  19.   ] [(conj history (peek new-knots)) (concat [head] new-knots)]))
  20.   [history knots]
  21.   (range steps)
  22. ))
  23.  
  24. (defn do-task [travel] (
  25.   -> travel first distinct count println
  26. ))
  27.  
  28. (with-open [rdr (clojure.java.io/reader "trail.in")] (
  29.   let [
  30.     lines (->> rdr
  31.       line-seq
  32.       (map #(clojure.string/split % #" "))
  33.       (map (fn [[dir steps]] [dir (Integer/parseInt steps)])))
  34.   ] (->> lines
  35.       (reduce travel [[[0 0]] [[0 0] [0 0]]])
  36.       do-task)
  37.     (->> lines
  38.       (reduce travel [[[0 0]] (vec (replicate 10 [0 0]))])
  39.       do-task)
  40. ))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement