Commit | Line | Data |
---|---|---|
3887e35c JK |
1 | (ns adventofcode2019.day03 |
2 | [:require [adventofcode2019.lib :refer :all] | |
3 | [clojure.string :as str] | |
4 | [clojure.set :as set] | |
5 | [clojure.math.combinatorics :as combo]]) | |
6 | ||
7 | (defn parse-input [input] | |
8 | (map #(str/split % #",") (str/split-lines (str/trim (slurp input))))) | |
9 | ||
10 | (defn spec->op [spec] | |
11 | (let [direction (first spec) | |
12 | distance (parse-int (str/join (rest spec)))] | |
13 | (case direction | |
14 | \U (fn [[x y]] [x (+ y distance)]) | |
15 | \D (fn [[x y]] [x (- y distance)]) | |
16 | \R (fn [[x y]] [(+ x distance) y]) | |
17 | \L (fn [[x y]] [(- x distance) y])))) | |
18 | ||
19 | ||
20 | (defn ints-between [x y] | |
21 | (cond | |
22 | (> x y) (range y (inc x)) | |
23 | (< x y) (range x (inc y)) | |
24 | :else [x])) | |
25 | ||
26 | (defn points-diff [pos-a pos-b] | |
27 | (let [[a-x a-y] pos-a | |
28 | [b-x b-y] pos-b] | |
29 | (set (for [x (ints-between a-x b-x) | |
30 | y (ints-between a-y b-y)] | |
31 | [x y])))) | |
32 | ||
33 | (defn wire-spec->points [wire] | |
34 | (let [wire-ops (map spec->op wire) | |
35 | trace-reduction (fn [{:keys [pos points]} op] | |
36 | (let [new-pos (op pos) | |
37 | new-points (points-diff pos new-pos)] | |
38 | {:pos new-pos :points (set/union points new-points)})) | |
39 | trace (reduce trace-reduction {:pos [0 0], :points #{}} wire-ops)] | |
40 | (:points trace))) | |
41 | ||
42 | (defn find-intersections [wires] | |
43 | (let [wires-points (map wire-spec->points wires)] | |
44 | (set/difference (apply set/intersection wires-points) #{[0 0]}))) | |
45 | ||
46 | (defn day03 [] | |
47 | (let [wires (parse-input (input-file)) | |
48 | manhattan-distance (fn [[x y]] (+ (Math/abs x) (Math/abs y))) | |
49 | intersections (find-intersections wires)] | |
50 | (println (apply min (map manhattan-distance intersections))))) |