]> code.bitgloo.com Git - clyne/advent-of-code.git/commitdiff
day2: revisit, make good
authorClyne Sullivan <clyne@bitgloo.com>
Mon, 13 Dec 2021 19:54:54 +0000 (14:54 -0500)
committerClyne Sullivan <clyne@bitgloo.com>
Mon, 13 Dec 2021 19:54:54 +0000 (14:54 -0500)
day2/part1.clj
day2/part2.clj

index d301b37179b4bdd4b9cd3c9ee03d840b93e5996f..65a287a517ad1d499c3cca87a20b6526ebd4ea1a 100644 (file)
@@ -1,4 +1,4 @@
-; Day 2, part 2
+; Day 2, part 1
 ; Read a list of instructions from stdin:
 ;   "down X" increases depth number by X,
 ;   "up X" decreases depth by X,
@@ -8,24 +8,19 @@
 
 (require '[clojure.string :as str])
 
-(loop [data {:xpos 0 :depth 0}]
-  (let [input (read-line)]
-    (if (empty? input)
-      (println (apply * (vals data)))
-      (let [ins (str/split input #" ")
-            n (Integer/parseInt (second ins))
-            ]
-        (recur
-          (apply (partial update-in data)
-            (case (first ins)
-              "forward" [[:xpos] + n]
-              "up" [[:depth] - n]
-              "down" [[:depth] + n]
-              )
-            )
-          )
-        )
-      )
-    )
-  )
+(println
+  (keduce *
+    (vals
+      (reduce
+        #(case (first %2)
+           "forward" (update %1 :xpos  + (second %2))
+           "up"      (update %1 :depth - (second %2))
+           "down"    (update %1 :depth + (second %2))
+           )
+        {:xpos 0 :depth 0}
+        (->> (slurp "./in")
+             str/split-lines
+             (map #(str/split % #" "))
+             (map #(update % 1 read-string))
+             )))))
 
index 7eeeb214342a476a5556aca9c703329bfbb7d342..9487a493b5f62aff4f95922f652e9b871fb47d1e 100644 (file)
@@ -8,25 +8,20 @@
 
 (require '[clojure.string :as str])
 
-(loop [data {:xpos 0 :depth 0 :aim 0}]
-  (let [input (read-line)]
-    (if (empty? input)
-      (println (apply * (map data [:xpos :depth])))
-      (let [ins (str/split input #" ")
-            n (Integer/parseInt (second ins))
-            ]
-        (recur
-          (case (first ins)
-            "forward" (-> data
-                          (update-in [:xpos] + n)
-                          (update-in [:depth] + (* (data :aim) n))
-                          )
-            "up" (update-in data [:aim] - n)
-            "down" (update-in data [:aim] + n)
-            )
-          )
-        )
-      )
-    )
-  )
+(println
+  (apply *
+    (map
+      (reduce
+        #(case (first %2)
+           "forward" (-> %1 (update :xpos + (second %2))
+                            (update :depth + (* (%1 :aim) (second %2))))
+           "up"      (update %1 :aim - (second %2))
+           "down"    (update %1 :aim + (second %2)))
+        {:xpos 0 :depth 0 :aim 0}
+        (->> (slurp "./in")
+             str/split-lines
+             (map #(str/split % #" "))
+             (map #(update % 1 read-string))))
+      [:xpos :depth]
+      )))