Created
December 8, 2019 22:48
-
-
Save MarcoNicolodi/024a2d9db26b136a5581e682b9a4564f to your computer and use it in GitHub Desktop.
advent of code day 3 part 1
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(ns advent-of-code-2019.day-3 | |
(:require [clojure.string :as str] | |
[clojure.set :as set])) | |
(def letter->direction {"R" :right "L" :left "U" :up "D" :down}) | |
(defn str->direction+distance [[dir & dists]] | |
{:direction (letter->direction (str dir)) | |
:distance (Integer/parseInt (str/join dists))}) | |
(defn move [[x y] [dir dist]] | |
(for [i (range 1 (inc dist))] | |
(case dir | |
:right [(+ x i) y] | |
:left [(- x i) y] | |
:up [x (+ y i)] | |
:down [x (- y i)]))) | |
(defn points->intersection [cartesian-points] | |
(->> cartesian-points | |
(map set) | |
(apply set/intersection))) | |
(defn manhattan-distance [[x1 y1] [x2 y2]] | |
(+ (Math/abs (- x2 x1)) (Math/abs (- y2 y1)))) | |
(def manhattan-distance-from-origin (partial manhattan-distance [0 0])) | |
(defn point+manhattan-distance [point] | |
{:point point :manhattan-distance (manhattan-distance-from-origin point)}) | |
(defn direction+distance->cartesian-points [dir+dist] | |
(reduce (fn [points d+d] (concat points (move (last points) (vals d+d)))) | |
[[0 0]] | |
dir+dist)) | |
(defn wire->internal [input] | |
(->> (str/split input #",") | |
(map str->direction+distance))) | |
(defn main [] | |
(-> (slurp "day_3.in") | |
(str/split #"\n") | |
(->> (mapv (comp direction+distance->cartesian-points wire->internal)) | |
points->intersection | |
(map point+manhattan-distance) | |
(sort-by :manhattan-distance)))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment