Guest User

Untitled

a guest
Dec 3rd, 2019
126
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. (ns manhattan.core
  2.   (:require [clojure.main :refer [main]]
  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 intersections [line-a line-b]
  25.   (for [[ax ay] line-a
  26.         [bx by] line-b
  27.         :when (and (= ax bx) (= ay by))]
  28.     [ax ay]))
  29.  
  30. (defn mh-dist [[ax ay] [bx by]]
  31.   (+ (Math/abs (- ax bx))
  32.      (Math/abs (- ay by))))
  33.  
  34. (defn min-dist [start dists]
  35.   (->> dists
  36.        (map (partial mh-dist start))
  37.        (apply min)))
  38.  
  39. (def parse-list
  40.   (partial
  41.    map
  42.    (fn [[d & num]]
  43.      [(keyword (lower-case d))
  44.       (Integer/parseInt (apply str num))])))
  45.  
  46. (defn parse-input [string]
  47.   (let [[a b] (->> string
  48.                    split-lines
  49.                    (map #(split % #",")))]
  50.     [(parse-list a) (parse-list b)]))
  51.  
  52. (defn -main []
  53.   (let [data (parse-input
  54.               (slurp "input.txt"))
  55.         [a b] (map (partial trace-line [0 0]) data)
  56.         dist (min-dist [0 0] (intersections a b))]
  57.     (println dist)))
  58.  
  59. (main (-main))
RAW Paste Data