Skip to content

Commit

Permalink
Day 06: Solve part 1 and 2
Browse files Browse the repository at this point in the history
  • Loading branch information
nihas101 committed Dec 6, 2023
1 parent a6083f0 commit d17639b
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 12 deletions.
42 changes: 39 additions & 3 deletions src/advent_of_code_2023/day06.clj
Original file line number Diff line number Diff line change
@@ -1,9 +1,45 @@
(ns advent-of-code-2023.day06
(:require
[clojure.math :as math]
[clojure.string :as string]
[advent-of-code-2023.utils.string :as u]))

(defn parse-input [input])
(defn parse-input [input prep-fun]
(let [[time distance] (mapv (fn [s] (re-seq #"\d+" (prep-fun s)))
(u/split-sections input u/line-endings))]
(mapv (fn [t d] {:duration t
:record d})
(mapv #(Long/parseLong %) time)
(mapv #(Long/parseLong %) distance))))

(defn day06-1 [parsed-input])
(defn- error-margin-brute-force [{:keys [^long duration ^long record]}]
(loop [button-hold-time 0
ways-to-beat-the-record []]
(let [boat-distance (* button-hold-time (- duration button-hold-time))]
(cond
;; We have checked every amount of time possible
(<= duration button-hold-time) ways-to-beat-the-record
;; We beat the record
(< record (* button-hold-time (- duration button-hold-time)))
(recur (inc button-hold-time)
(conj ways-to-beat-the-record {:hold-time button-hold-time :distance boat-distance}))
:else (recur (inc button-hold-time)
ways-to-beat-the-record)))))

(defn day06-2 [parsed-input])
(defn day06-1 [input]
(transduce
(comp
(map error-margin-brute-force)
(map count))
* (parse-input input identity)))

(defn- error-margin [{:keys [^long duration ^long record]}]
(let [d (math/sqrt (- (* duration duration) (* 4 (- 1) (- (inc record)))))]
[(long (quot (+ (- duration) d) (* 2 (- 1))))
(long (quot (- (- duration) d) (* 2 (- 1))))]))

(defn day06-2 [input]
(let [[^long a ^long b] (error-margin
(first
(parse-input input #(string/replace % #"\s+" ""))))]
(- b a)))
15 changes: 6 additions & 9 deletions test/advent_of_code_2023/day06_test.clj
Original file line number Diff line number Diff line change
Expand Up @@ -4,26 +4,23 @@
[advent-of-code-2023.day06 :refer :all]
[advent-of-code-2023.test-utils :as tu]))

(def ^:private example-input "")
(def ^:private example-input "Time: 7 15 30
Distance: 9 40 200")

(def ^:private input (tu/slurp-input "resources/day06.txt"))

(deftest day06-1-example-test
(testing "day06-1 example"
(is (= nil
(day06-1 example-input)))))
(is (= 288 (day06-1 example-input)))))

(deftest day06-1-test
(testing "day06-1"
(is (= nil
(day06-1 input)))))
(is (= 633080 (day06-1 input)))))

(deftest day06-2-example-test
(testing "day06-2 example"
(is (= nil
(day06-2 example-input)))))
(is (= 71503 (day06-2 example-input)))))

(deftest day06-2-test
(testing "day06-2"
(is (= nil
(day06-2 input)))))
(is (= 20048741 (day06-2 input)))))

0 comments on commit d17639b

Please sign in to comment.