Skip to content

Instantly share code, notes, and snippets.

@quephird
Created December 5, 2022 20:02
Show Gist options
  • Save quephird/f7e153cc83f30155d538268b9a626eb9 to your computer and use it in GitHub Desktop.
Save quephird/f7e153cc83f30155d538268b9a626eb9 to your computer and use it in GitHub Desktop.
(require ['clojure.string :as 'str])
(def stacks
{1 ["Q" "M" "G" "C" "L"]
2 ["R" "D" "L" "C" "T" "F" "H" "G"]
3 ["V" "J" "F" "N" "M" "T" "W" "R"]
4 ["J" "F" "D" "V" "Q" "P"]
5 ["N" "F" "M" "S" "L" "B" "T"]
6 ["R" "N" "V" "H" "C" "D" "P"]
7 ["H" "C" "T"]
8 ["G" "S" "J" "V" "Z" "N" "H" "P"]
9 ["Z" "F" "H" "G"]})
(defn crane-9000 [stacks num-crates from-stack-num to-stack-num]
(loop [n num-crates
from-stack (stacks from-stack-num)
to-stack (stacks to-stack-num)]
(if (zero? n)
(-> stacks
(assoc from-stack-num from-stack)
(assoc to-stack-num to-stack))
(let [new-crate (peek from-stack)]
(recur (dec n)
(pop from-stack)
(conj to-stack new-crate))))))
(defn crane-9001 [stacks num-crates from-stack-num to-stack-num]
(let [new-from-stack (vec (drop-last num-crates (stacks from-stack-num)))
moved-crates (vec (take-last num-crates (stacks from-stack-num)))
new-to-stack (vec (concat (stacks to-stack-num) moved-crates))]
(-> stacks
(assoc from-stack-num new-from-stack)
(assoc to-stack-num new-to-stack))))
(defn parse-line [line]
(let [[_ num-crates _ from-stack-num _ to-stack-num] (str/split line #" ")]
(map #(Integer/parseInt %) [num-crates from-stack-num to-stack-num])))
(defn process-all-moves [stacks crane all-moves]
(loop [[current-move & rest-of-moves] all-moves
stacks* stacks]
(if (nil? current-move)
stacks*
(recur rest-of-moves (apply crane stacks* current-move)))))
(defn tops-of-stacks [stacks]
(->> (range 1 10)
(reduce #(concat %1 (last (stacks %2))) "")
(apply str)))
(defn solution-part-1 [filename]
(->> filename
slurp
str/split-lines
(map parse-line)
(process-all-moves stacks crane-9000)
tops-of-stacks))
(defn solution-part-2 [filename]
(->> filename
slurp
str/split-lines
(map parse-line)
(process-all-moves stacks crane-9001)
tops-of-stacks))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment