aoc2021-day03a Clojure/Babashka program
source code
; SPDX-License-Identifier: MIT
; Copyright (C) 2021 Tito Sacchi <tito@tilde.team>
; WARNING: These solutions were written while I was still learning Clojure and
; should by no means be taken as examples of good programming practice or fast
; implementations.
(ns aoc.2021.03a)
(defn parse-line [line] (map #(Integer/parseInt (str %)) line))
(defn update-counts [counts line]
(->> line
(parse-line)
(map #(update %1 %2 inc) counts)))
(def most-common-bits
(->> *in*
(java.io.BufferedReader.)
(line-seq)
(reduce update-counts (repeat {0 0, 1 0}))
(map #(key (apply max-key val %)))))
(defn from-bin [xs]
(reduce
#(case %2
0 (* 2 %1)
1 (inc (* 2 %1))) xs))
(def gamma (from-bin most-common-bits))
(def epsilon (from-bin (map #(- 1 %) most-common-bits)))
(println (* gamma epsilon))
notes, command-line, and program output
NOTES:
Linux
Sun, 23 Jan 2022 12:52:29 GMT
COMMAND LINE:
bb -f aoc2021_day03a.clj_babashka-1.clj_babashka 0 < aoc2021_day03a-input100000.txt
PROGRAM FAILED
PROGRAM OUTPUT:
----- Error --------------------------------------------------------------------
Type: java.lang.StackOverflowError
Location: /bencher/tmp/aoc2021_day03a/tmp/aoc2021_day03a.clj_babashka-1.clj_babashka:24:3
----- Context ------------------------------------------------------------------
20: (reduce update-counts (repeat {0 0, 1 0}))
21: (map #(key (apply max-key val %)))))
22:
23: (defn from-bin [xs]
24: (reduce
^---
25: #(case %2
26: 0 (* 2 %1)
27: 1 (inc (* 2 %1))) xs))
28:
29: (def gamma (from-bin most-common-bits))
----- Stack trace --------------------------------------------------------------
clojure.core/seq--5435 - <built-in>
clojure.core/map/fn--5904 - <built-in>
clojure.core/seq--5435 - <built-in>
clojure.core/map/fn--5904 - <built-in>
clojure.core/seq--5435 - <built-in>
... (run with --debug to see elided elements)
clojure.core/map/fn--5904 - <built-in>
clojure.core/reduce - <built-in>
aoc.2021.03a/from-bin - /bencher/tmp/aoc2021_day03a/tmp/aoc2021_day03a.clj_babashka-1.clj_babashka:24:3
aoc.2021.03a/from-bin - /bencher/tmp/aoc2021_day03a/tmp/aoc2021_day03a.clj_babashka-1.clj_babashka:23:1
aoc.2021.03a - /bencher/tmp/aoc2021_day03a/tmp/aoc2021_day03a.clj_babashka-1.clj_babashka:29:12