Skip to content

Instantly share code, notes, and snippets.

@joinr
Last active January 3, 2021 19:57
Show Gist options
  • Save joinr/0d4d3ea0e6544947744949b08d064ad5 to your computer and use it in GitHub Desktop.
Save joinr/0d4d3ea0e6544947744949b08d064ad5 to your computer and use it in GitHub Desktop.
aoc2020-23
(ns aoc2020.demo)
(def demo [3 8 9 1 2 5 4 6 7])
;;transcribed from https://www.youtube.com/watch?v=5AqX3Wu00ok
(defn cups->circle ^longs [cups-prefix ^long total-cups]
(let [circle (long-array (inc total-cups))]
(doseq [[a b] (partition 2 1 cups-prefix)]
(aset-long circle a b))
(loop [a (last cups-prefix)
b (inc (count cups-prefix))]
(if (<= b total-cups)
(do (aset-long circle a b)
(recur b (inc b)))
(aset-long circle a (first cups-prefix))))
circle))
(defn destination [^longs circle ^long current ^long x ^long y]
(let [destination (dec (if (= 1 current) (long (alength circle)) current))]
(if (or (= x destination)
(= y destination)
(= (aget circle y) destination))
(recur circle destination x y)
destination)))
(defn play-crab-cups [^longs circle ^long current ^long steps]
(if (zero? steps)
circle
(let [x (aget circle current)
y (aget circle x)
z (aget circle y)
next (aget circle z)
destination (destination circle current x y)]
(aset-long circle current next)
(aset-long circle z (aget circle destination))
(aset-long circle destination x)
(recur circle next (dec steps)))))
(defn traverse [^longs circle]
(->> (aget circle 1)
(iterate (partial aget circle))
(take 8)
clojure.string/join))
(defn play [xs current length steps]
(let [circle (cups->circle xs length)]
(play-crab-cups circle current steps)
(traverse circle)))
(defn test-games [n]
(for [i (range 10)] (play demo 1 9 i)))
(def move-states
[[3 8 9 1 2 5 4 6 7]
[3 2 8 9 1 5 4 6 7]
[3 2 5 4 6 7 8 9 1]
[7 2 5 8 9 1 3 4 6]
[3 2 5 8 4 6 7 9 1]
[9 2 5 8 4 1 3 6 7]
[7 2 5 8 4 1 9 3 6]
[8 3 6 7 4 1 9 2 5]
[7 4 1 5 8 3 9 2 6]
[5 7 4 1 8 3 9 2 6]
[5 8 3 7 4 1 9 2 6 ]])
(def moves (mapv #(traverse (cups->circle % 9)) move-states))
;; aoc2020.demo> (map vector moves (test-games 10))
;; (["25467389" "25467389"]
;; ["54673289" "67389254"]
;; ["32546789" "69257384"]
;; ["34672589" "69382574"]
;; ["32584679" "82569374"]
;; ["36792584" "89372564"]
;; ["93672584" "56489372"]
;; ["92583674" "89564372"]
;; ["58392674" "84379562"]
;; ["83926574" "84562379"])
(def move10 "92658374")
(def move100 "67384529")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment