-
-
Save galuque/b7d60d2f2ac4c9b4658b4d21f02b12df to your computer and use it in GitHub Desktop.
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 io.github.galuque.aoc-2021.day-2 | |
(:require [clojure.java.io :as io] | |
[clojure.string :as str])) | |
(def input | |
(->> "day_2/input.txt" | |
io/resource | |
slurp)) | |
(def sample-input "forward 5 | |
down 5 | |
forward 8 | |
up 3 | |
down 8 | |
forward 2") | |
(defn parse-input [input] | |
(->> input | |
str/split-lines | |
(map (fn [s] (str/split s #" "))) | |
(map (fn [[direction amount]] [(keyword direction) (parse-long amount)])))) | |
(def parsed-sample-input (parse-input sample-input)) | |
(def parsed-input (parse-input input)) | |
(def inital-position {:horizontal 0 | |
:depth 0 | |
:aim 0}) | |
(defn next-position [current-position [instruction amount]] | |
(case instruction | |
:forward (update current-position :horizontal + amount) | |
:down (update current-position :depth + amount) | |
:up (update current-position :depth - amount))) | |
(defn final-product [{:keys [horizontal depth]}] | |
(* horizontal depth)) | |
(defn part-1 [input] | |
(->> input | |
(reduce next-position inital-position) | |
final-product)) | |
(comment | |
(part-1 parsed-sample-input) | |
;; => 150 | |
(part-1 parsed-input) | |
;; => 1727835 | |
) | |
(defn next-position-2 [current-position [instruction amount]] | |
(case instruction | |
:forward (-> current-position | |
(update :horizontal + amount) | |
(update :depth + (* amount (:aim current-position)))) | |
:down (update current-position :aim + amount) | |
:up (update current-position :aim - amount))) | |
(defn part-2 [input] | |
(->> input | |
(reduce next-position-2 inital-position) | |
final-product)) | |
(comment | |
(part-2 parsed-sample-input) | |
;; => 900 | |
(part-2 parsed-input) | |
;; => 1544000595 | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment