Skip to content

Instantly share code, notes, and snippets.

@devn

devn/day7.clj Secret

Created December 8, 2020 21:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save devn/b7b961b41e6f6f2e864a960a4fece130 to your computer and use it in GitHub Desktop.
Save devn/b7b961b41e6f6f2e864a960a4fece130 to your computer and use it in GitHub Desktop.
clara-based solve of Part I of Day 7 Advent of Code
(defrecord ContainerBag [type contained-bags])
(defrecord IntermediateBag [parent-type type])
(defrecord GoldBag [parent-type])
(defrule produce-intermediate-bags
[ContainerBag
(= ?type type)
(= ?contained-bags contained-bags)]
=>
(when (seq ?contained-bags)
(insert-all!
(mapv (fn [[kind num]]
(if (= kind "shiny gold")
(map->GoldBag {:parent-type ?type})
(map->IntermediateBag {:parent-type ?type
:type kind})))
?contained-bags))))
(defrule indirect-gold-bags
[ContainerBag
(= ?type type)]
[IntermediateBag
(= ?type parent-type)
(= ?intermediate-type type)]
[GoldBag
(= ?intermediate-type parent-type)]
=>
(insert! (map->GoldBag {:parent-type ?type})))
(defquery gold-bags []
[?gold-bags <- (acc/distinct :parent-type) :from [GoldBag]])
(defn run-rules []
(-> (mk-session :cache false)
(insert-all (doall (for [[k vs] (parse input)]
(map->ContainerBag {:type k
:contained-bags vs}))))
(fire-rules)))
;; Part I
(-> (run-rules)
(query gold-bags)
first
:?gold-bags
count)
;; => 179
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment