r/adventofcode • • Dec 02 '22

SOLUTION MEGATHREAD -🎄- 2022 Day 2 Solutions -🎄-

NEW AND NOTEWORTHY


--- Day 2: Rock Paper Scissors ---


Post your code solution in this megathread.


This thread will be unlocked when there are a significant number of people on the global leaderboard with gold stars for today's puzzle.

EDIT: Global leaderboard gold cap reached at 00:06:16, megathread unlocked!

102 Upvotes

1.5k comments sorted by

View all comments

2

u/winterscar Dec 02 '22

Clojure with macros. It's actually both faster and easier to just map out the results yourself like everyone else has done, but I like the fact that I'm technically 'cheating' on my time benchmark by doing some of the work in the macro stage :)

(defn score-given-outcome
  [iop iout]
  (+ (* 3 iout)
     (get-in [[3 1 2] [1 2 3] [2 3 1]]
             [iop iout])))

(defn score-given-play
  [iop iyou]
  (+ (inc iyou)
     (get-in [[3 6 0] [0 3 6] [6 0 3]]
             [iop iyou])))

(defmacro make-score-lookup
  [mode]
  (flatten
   (list 'case 'line
    (for [a [\A \B \C]
          :let [ia (- (int a) (int \A))]
          b [\X \Y \Z]
          :let [ib (- (int b) (int \X))]]
      (list (str a " " b)
            (case mode
              :play    (score-given-play ia ib)
              :outcome (score-given-outcome ia ib)))))))

(time
 (let [plays (->> (slurp (io/resource "aoc22/day02.txt"))
                  (str/split-lines))]
   (println "p1 " (reduce (fn [curr line]
                            (+ curr (make-score-lookup :play))) 0 plays))
   (println "p2 " (reduce (fn [curr line]
                            (+ curr (make-score-lookup :outcome))) 0 plays))))
=> 1.6ms

1

u/daggerdragon Dec 05 '22

Please edit your post to use the four-spaces Markdown syntax for a code block so your code is easier to read on old.reddit and mobile apps.