adventofcode 2026-12-02

part 1

(def pat "roygbv")
(def n (count pat))
(def patpat (str pat pat))

(def dist
  (reduce
   conj
   {}
   (map-indexed
    (fn [i cfrom]
      (reduce
       (fn [acc [k v]]
         (assoc-in acc k v))
       {}
       (for [cto pat]
         [[cfrom cto] (- (String/.indexOf patpat (int cto) (int (inc i))) i)])))
    pat)))

(defn travel
  [^String xs]
  (let [end (count xs)]
    (loop [curr \r
           i 0
           tot 0]
      (if (== i end)
        tot
        (let [c (String/.charAt xs i)
              d (-> dist (get curr) (get c))]
          (recur c (inc i) (+ tot d)))))))

(= (travel "obbvb") 16)
(= (travel "roygbv") 11)
(= (travel "vbgyor") 30)
(= (travel "vvvvvv") 35)

Not a fan of my part 2 solution, wanted one where I don’t reconstruct the string, I guess I’m close to it though

(defn best-transitions
  [ks]
  (loop [k (first ks)
         ks' (set (rest ks))
         acc {}]
    (if (seq ks')
      (let [[k' v] (apply max-key val (filter (comp ks' key) (dissoc (get dist k) k)))]
        (recur k' (disj ks' k') (assoc acc k k')))
      acc)))

(best-transitions (filter (frequencies input) pat))

(defn compressed [transitions]
  (loop [c \r
         acc []
         transitions transitions]
    (if (empty? transitions)
      (conj acc c)
      (recur (get transitions c) (conj acc c) (dissoc transitions c)))))

(compressed (best-transitions (filter (frequencies input) pat)))

(defn rearranged
  [input]
  (let [freqs (frequencies input)
        bests (best-transitions (filter freqs pat))
        input (compressed bests)]
    (mapcat (fn [c] (repeat (get freqs c) c)) input)))

(= (rearranged "rybryb") (seq "rrbbyy"))

(defn solve2
  [input]
  (->> input
       rearranged
       (apply str)
       travel))

I just realized that my working solution had a bug, but it turns out that the bug is actually a valid optimization 🤣🤣🤣 Or maybe I was lucky. Not sure.

okay, this also works

(defn travel-compressed
  [xs freqs]
  (let [r (get freqs \r)
        freqs (dissoc freqs \r)
        transitions (partition 2 1 xs)]
    (+
     (* 6 r)
     (reduce + 0 (map (partial * 6) (map dec (vals freqs))))
     (reduce + 0 (for [t transitions]
                   (get-in dist t))))))


(defn solve2'
  [input]
  (let [freqs (frequencies input)]
    (travel-compressed (compressed (best-transitions (filter freqs pat))) freqs)))

Today I give you two versions of Part 2 solution: • the initial one (I hope I managed to explain what’s going on there; let me know if I failed) • the one I came up with after some experimenting on paper, and it is basically one-liner that gives the solution instantly (nanoseconds) https://narimiran.github.io/aoc2026/day02.html

👏 2

Seems like I constantly think too complicated 😄 If the program (as in the input data) is longer than the waypoints string, does that imply that we should assume periodic boundary conditions? I.e. start from the beginning once there are no waypoints left?

Maybe that is hinted via the “…”

I think that Narimiran was pretty close to the right formula for the simplified part 2. I think that the correct and general solution involves substracting (apply min data) instead of (dec wp-len)

@aaronrebmann yes, waypoints repeat in infinity.

Valentin De Negri Fischer 2026-12-02T12:48:05.786459Z

;; Infinite seq of waypoints
(def waypoints
  (cycle '(:r :o :y :g :b :v)))

(comment
  (take 20 waypoints))
;; Decode progam into seq of keywords,
;; necessary to access frequency map in part two

(defn program-str->keyword-seq
  [program-str]
  (map (comp keyword str) (seq program-str)))
(comment
  (program-str->keyword-seq program))
;; PART 1
;;Counting way between two endpoints
(comment
  (let [start :r
        end :v]
    (count
     (take-while
      #(not (= end %))
      (drop-while
       #(not (= start %))
       waypoints)))))

(defn count-waypoints
  [start end waypoints]
  (if (= start end)
    6
    (count (take-while
            #(not (= end %))
            (drop-while
             #(not (= start %))
             waypoints)))))
(comment
  (count-waypoints :r :o waypoints)
  (count-waypoints :o :b waypoints)
  (count-waypoints :b :b waypoints)
  (count-waypoints :b :v waypoints)
  (count-waypoints :v :b waypoints))

;; For every distance calculate and sum up result
(defn run-programm
  [first-point program waypoints]
  (let [parsed-program (program-str->keyword-seq program)
        [_ res]
        (reduce (fn [[start-point counter] val]
                  [val (+ counter (count-waypoints start-point val waypoints))])
                [first-point 0]
                parsed-program)]
    res))

(run-programm :r program waypoints)

;;
;; Part 2
;;
(comment
  "Playing around with getting a list of waypoints
  sorted by length from startpoint"
  (drop 1 (take 7 waypoints))
  (let [start :b]
    (reverse
     (drop 1
           (take 7
                 (drop-while
                  #(not (= start %))
                  waypoints))))))

(defn calc-waypoints-by-length
  [start waypoints]
  (reverse
   (drop 1
         (take 7
               (drop-while
                #(not (= start %))
                waypoints)))))
;; Calculate the frequency of each step in the programm
;; then run through the filtere optimal order and re-
;; construct the programm
(defn calc-optimal-way
  [start-point program waypoints]
  (let [parsed-program (program-str->keyword-seq program)
        optimal-waypoint-order (filter
                                (set parsed-program)
                                (calc-waypoints-by-length start-point waypoints))
        freq-by-waypoint (frequencies parsed-program)]
    (->> optimal-waypoint-order
         (map (fn [wp]
                (let [amount (wp freq-by-waypoint)]
                  (repeat amount wp))))
         (flatten)
         (map name)
         (apply str))))
(let [optimized-pr (calc-optimal-way :r program waypoints)]
  (run-programm :r optimized-pr waypoints))

Valentin De Negri Fischer 2026-12-02T12:54:55.757579Z

still new to clojure so any feedback wellcomed 🙂 like is this ideomatic and is there more performant ways?

@valentin.denegrifisch take-while + drop-while = split-with (also, do not show input string since it’s against the AoC rules)

👍 1

Another two hints: string itself is a sequence of chars, so you don’t need to use keywords and convert it from/to - just use chars directly (“abc” <-> [\a \b \c]). Second one is kind of hack - when you compare to a single value you can use a set #(= goal %) ↔ (#{goal} v) #{goal} is a predicate itself, complementary predicate can be created with complement (to nagate the outcome).

Works for the examples, but just runs forever on the real data - skimming the other solutions, my approach is probably too complicated so I might be overlooking a lazy sequence that I am realizing somewhere

If I had noticed from the start that the waypoints are just a repeating pattern, I would have chosen a different approach. The lazy sequences came in there more of as an afterthought

Valentin De Negri Fischer 2026-12-02T13:43:11.829299Z

@tsulej Hey thanks so much for the tipps, really much appreciated. I started with a seq of chars in the beginning and the when i wanted to get the frequency of one of them i realized i cannot lookup a map by char? but now reading the other solutions i think i just used get wrongly 😞

Valentin De Negri Fischer 2026-12-02T13:43:44.938359Z

using set as a predicate is super neat, i still tend to forget about it.

👍 1

After having great joy last year solving AoC in Clojure I am doing it again this year, here's my solution For day 2 https://github.com/code-shoily/aoclj/blob/main/src/aoclj/year_2026/day_02.clj

My solution 🙂

(def colors [\r \o \y \g \b \v])

;; for part two the ordering that gives us the max-distance
;; starts with r and continues with the reverse of the other items
(def max-order
  (zipmap
   (cons (first colors) (reverse (rest colors)))
   (range)))

(defn pair-distance [from to]
  (let [s (.indexOf colors from)
        e (.indexOf colors to)
        d (mod (- e s) (count colors))]
    (if (zero? d) 6 d)))

(defn distance [s]
  (reduce + (map pair-distance (cons \r s) s)))

(defn rearrange [s]
  (apply str (sort-by max-order s)))

(defn max-distance [s]
  (distance (rearrange s)))

(comment
  (= 16 (distance "obbvb"))
  (= 11 (distance "roygbv"))
  (= 30 (distance "vbgyor"))
  (= 35 (distance "vvvvvv"))

  (= "rvvvbg" (rearrange "vrvbvg"))
  (= 33 (max-distance "vrvbvg"))
  (= 55 (max-distance "groovyyoyo"))
  (= 103 (max-distance "roygbvroygbvroygbv"))

❤️ 1

@code-shoily nice use of partial!

@trevor673 from what I’ve seen, every input has one missing letter

I suspected as much. Done enough of these to know there’s often some edge case built into the input!

👍 1

I haven’t read y’all’s solutions yet, but I thought I’d ask before I start reading for efficient concurrency. 😉 I’m pretty happy with my solution, but I feel like the distance function in particular is written a bit clunkily. Thoughts?

(defn distance [[from to]]
  (let [get-idx (partial str/index-of "roygbv")
        d       (mod (+ 6 (- (get-idx to)
                             (get-idx from)))
                     6)]
    (if (= 0 d)
      6
      d)))

(defn walk [s]
  (->> (str/split (str "r" s) #"")
       (partition 2 1)
       (map distance)
       (reduce +)))

(defn part1 [s]
  (walk s))

(defn part2 [s]
  (->> (frequencies s)
       (sort-by #(- (distance [\r (first %)])))
       (mapcat (fn [[ch n]] (repeat n ch)))
       (apply str)
       walk))

You can avoid the mod math by concatting another repetition of the pattern and calculating distance based on that

@soltanzadehramin first thing I noticed: you don’t have to add 6 in mod, it handles negatives for you

☝️ 1

I considered appending just "r" , and that obviously wouldn’t work. Didn’t continue that train of throught to realize I could duplicate the whole thing. Also nice one about negative numbers. I had no idea.

The other thing: the distances are constant, you can/should calculate them only once. No need to do str/index-of every time.

I was anticipating the order of waypoints to change in part2, so I thought I was being smart. But I should still have memoized it probably, yes.

I think I was thinking of memoizing, I just forgot.

That’s just a matter of calling clojure’s memoize, right?

No need for big guns. A simple char->dist (hash)map is enough.

I’d imagine that’s what memoize does. Now I’m curious what it actually does.

(defn memoize
  "Returns a memoized version of a referentially transparent function. The
  memoized version of the function keeps a cache of the mapping from arguments
  to results and, when calls with the same arguments are repeated often, has
  higher performance at the expense of higher memory use."
  {:added "1.0"
   :static true}
  [f]
  (let [mem (atom {})]
    (fn [& args]
      (if-let [e (find @mem args)]
        (val e)
        (let [ret (apply f args)]
          (swap! mem assoc args ret)
          ret)))))
Yeah, it’s a simple hashmap cache utility.

As @narimiran said: no need for big guns, it’s enough to have {\r 0 \v 1 \b 2 \g 3 \y 4 \o 5} set manually.

☝️ 1

...or, if you don’t want to do it manually, take a look at my solution to see how to use zipmap for creating the same thing

Yeah, zipmap was a cool trick.

Was able to solve part 2 in terms of part 1 by sorting the input by "oygbvr". Also didn’t need any addition; just needed to keep track of an index from an infinite seq. https://github.com/brandoncorrea/advent-of-code/blob/master/clojure/src/aoc/y2026/day02.cljc

1
Valentin De Negri Fischer 2026-12-02T14:30:29.167509Z

where do you follow other communities results?

Past years on reddit, but I havent checked this year yet

There is r/adventofcode. Though it seems like it is not as organizes as usual. In prior years, there were solution megathreads, basically the same principle we have here, but I haven't found them this year on reddit yet

1
Valentin De Negri Fischer 2026-12-02T14:45:17.665999Z

thanks @aaronrebmann

I just realize that the text in the Day 1 puzzle mentions about December 12th. Will it be the last puzzle?

1

my understanding is that advent of code will continue to be first 12 days of december (instead of 30 days)

Yes, it is 12 tasks, like last year.

oh, and I even replied the annoucement but forgot 😅 https://functional.cafe/@greenCoder/115415874346032768

😀 1