Guest User

AoC Day 3

a guest
Dec 3rd, 2019
105
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. (ns manhattan.core
  2.   (:require [clojure.set :refer [intersection]]
  3.             [clojure.string :refer [lower-case split split-lines]]))
  4.  
  5. (def pos
  6.   {:u inc :d dec
  7.    :r inc :l dec})
  8.  
  9. (defn path-inc [cord [k v]]
  10.   (let [dir (if (contains? #{:u :d} k) 1 0)
  11.         choose #(update % dir (pos k))]    
  12.     (take v (rest (iterate choose cord)))))
  13.  
  14. (defn trace-line [start dirs]
  15.   (let [llast #(last (last %))
  16.         reducer (fn [acc dir]
  17.                   (conj acc (path-inc (llast acc) dir)))]
  18.     (->> dirs
  19.          (reduce reducer [[start]])
  20.          flatten
  21.          (partition 2)
  22.          rest)))
  23.  
  24. (defn mh-dist [[ax ay] [bx by]]
  25.   (+ (Math/abs (- ax bx))
  26.      (Math/abs (- ay by))))
  27.  
  28. (defn min-dist [start dists]
  29.   (->> dists
  30.        (map (partial mh-dist start))
  31.        (apply min)))
  32.  
  33. (defn least-cost [intersections [a-trace b-trace]]
  34.   (->> intersections
  35.        (map (fn [pos]
  36.               (let [cost #(count (take-while (partial not= pos) %))]
  37.                 (+ (cost a-trace) (cost b-trace) 2))))
  38.        (apply min)))
  39.  
  40. (def parse-list
  41.   (partial
  42.    map
  43.    (fn [[d & num]]
  44.      [(keyword (lower-case d))
  45.       (Integer/parseInt (apply str num))])))
  46.  
  47. (defn parse-input [string]
  48.   (let [[a b] (->> string
  49.                    split-lines
  50.                    (map #(split % #",")))]
  51.     [(parse-list a) (parse-list b)]))
  52.  
  53. (defn -main []
  54.   (let [data (parse-input
  55.               (slurp "input.txt"))
  56.         [a b] (map (partial trace-line [0 0]) data)
  57.         intsec-points (intersection (set a) (set b))
  58.         dist (min-dist [0 0] intsec-points)]
  59.     (println dist)
  60.     (println (least-cost intsec-points [a b]))))
RAW Paste Data