Skip to content

Instantly share code, notes, and snippets.

@Solaxun
Created December 22, 2020 17:39
Show Gist options
  • Save Solaxun/92d3c438d290bc2a743f5d41d7bc4077 to your computer and use it in GitHub Desktop.
Save Solaxun/92d3c438d290bc2a743f5d41d7bc4077 to your computer and use it in GitHub Desktop.
Advent of Code 2020, Day 22... can't find the bug
(def game {:player1 [26 8 2 17 19 29 41 7 25 33 50 16 36 37 32 4 46 12 21 48 11 6 13 23 9],
:player2 [27 47 15 45 10 14 3 44 31 39 42 5 49 24 22 20 30 1 35 38 18 43 28 40 34]})
;; Treating the seen rule as needing to see the exact game (both decks) twice.
;; Doesn't terminate.
(defn play-round [game]
(loop [seen #{}
{:keys [player1 player2] :as game} game]
(if (or (empty? player1) (empty? player2))
game
(let [p1 (player1 0)
p2 (player2 0)
p1s (subvec player1 1)
p2s (subvec player2 1)
winner (cond (seen game) :player1
(and (<= p1 (count p1s)) (<= p2 (count p2s)))
(play-round {:player1 (subvec p1s 0 p1)
:player2 (subvec p2s 0 p2)})
:else (if (> p1 p2) :player1 :player2))]
(recur (conj seen game)
(if (= winner :player1)
{:player1 (conj p1s p1 p2) :player2 p2s}
{:player1 p1s :player2 (conj p2s p2 p1)}))))))
;; Treating the seen rule as meaning you must only see one deck twice.
;; Terminates but with wrong answer
(defn play-round [game]
(loop [seen #{}
{:keys [player1 player2] :as game} game]
(if (or (empty? player1) (empty? player2))
game
(let [p1 (player1 0)
p2 (player2 0)
p1s (subvec player1 1)
p2s (subvec player2 1)
winner (cond (or (seen (:player1 game))
(seen (:player2 game))) :player1
(and (<= p1 (count p1s)) (<= p2 (count p2s)))
(play-round {:player1 (subvec p1s 0 p1)
:player2 (subvec p2s 0 p2)})
:else (if (> p1 p2) :player1 :player2))]
(recur (into seen (vals game))
(if (= winner :player1)
{:player1 (conj p1s p1 p2) :player2 p2s}
{:player1 p1s :player2 (conj p2s p2 p1)}))))))
(defn score-game [game]
(->> game
(play-round)
vals
(keep seq)
first
reverse
(map-indexed (fn [i x] (* (inc i) x)))
(reduce +)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment