aoc2021-day06b 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.06b
(:require
[clojure.string :as str]))
(defn parse [line]
(vec (map #(Integer/parseInt %) (str/split line #","))))
(defn prdbg [x] (do (println x) x))
(defn ifnil [x y] (if (nil? x) y x))
(defn step [n freqs]
(loop [k 0
freqs freqs]
(if (= k n) freqs
(let [; decrease all keys by one
timers (reduce-kv #(assoc %1 (dec %2) %3) {} freqs)
new (get timers -1)]
(recur (inc k) (if (some? new)
(-> timers
(update 8 #(+ (ifnil % 0) new))
(update 6 #(+ (ifnil % 0) new))
(dissoc -1))
timers))))))
(let [freqs (->> (read-line) (parse) (frequencies))
n (->> (read-line) (Integer/parseInt))]
(println (-> (step n freqs)
(vals)
(apply +))))
notes, command-line, and program output
NOTES:
Linux
Sun, 23 Jan 2022 14:18:51 GMT
COMMAND LINE:
bb -f aoc2021_day06b.clj_babashka-1.clj_babashka 0 < aoc2021_day06b-input1.txt
PROGRAM FAILED
PROGRAM OUTPUT:
----- Error --------------------------------------------------------------------
Type: java.lang.ArithmeticException
Message: integer overflow
Location: /bencher/tmp/aoc2021_day06b/tmp/aoc2021_day06b.clj_babashka-1.clj_babashka:27:41
----- Context ------------------------------------------------------------------
23: new (get timers -1)]
24: (recur (inc k) (if (some? new)
25: (-> timers
26: (update 8 #(+ (ifnil % 0) new))
27: (update 6 #(+ (ifnil % 0) new))
^--- integer overflow
28: (dissoc -1))
29: timers))))))
30:
31: (let [freqs (->> (read-line) (parse) (frequencies))
32: n (->> (read-line) (Integer/parseInt))]
----- Stack trace --------------------------------------------------------------
clojure.lang.Numbers/LongOps - <built-in>
clojure.core/+ - <built-in>
aoc.2021.06b - /bencher/tmp/aoc2021_day06b/tmp/aoc2021_day06b.clj_babashka-1.clj_babashka:27:41
clojure.core/update - <built-in>
aoc.2021.06b - /bencher/tmp/aoc2021_day06b/tmp/aoc2021_day06b.clj_babashka-1.clj_babashka:27:30
... (run with --debug to see elided elements)
aoc.2021.06b - /bencher/tmp/aoc2021_day06b/tmp/aoc2021_day06b.clj_babashka-1.clj_babashka:35:19
clojure.core/apply - <built-in>
aoc.2021.06b - /bencher/tmp/aoc2021_day06b/tmp/aoc2021_day06b.clj_babashka-1.clj_babashka:36:19
clojure.core/println - <built-in>
aoc.2021.06b - /bencher/tmp/aoc2021_day06b/tmp/aoc2021_day06b.clj_babashka-1.clj_babashka:34:6