Created
January 28, 2023 16:29
-
-
Save seanstrom/f0d1119c24f4d3cb48de33b6ea59425c to your computer and use it in GitHub Desktop.
Puzzle 87 Solution
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(fn makeEquation [& data] | |
(let | |
[nums (into [] data) | |
inputs (pop nums) | |
output (peek nums) | |
operators ['+ '*] | |
formatOutput | |
(fn [expr] | |
`(~'= ~expr ~output)) | |
makeOperation | |
(fn [num operator] | |
`(~operator ~num)) | |
append | |
(fn [coll item] | |
(concat coll [item])) | |
combineTableKeys | |
(fn [other prevKey nextKey] | |
(cond | |
(empty? prevKey) | |
nextKey | |
(and | |
(empty? other) | |
(coll? (last prevKey)) | |
(= 2 (count (last prevKey)))) | |
(concat (butlast prevKey) | |
[(concat (last prevKey) (rest nextKey))]) | |
(and | |
(coll? (last prevKey)) | |
(= (first (last prevKey) (first nextKey)))) | |
(concat (butlast prevKey) | |
[(concat (last prevKey) (rest nextKey))]) | |
(or | |
(= (first prevKey) (first nextKey)) | |
(and (empty? other) (= 2 (count prevKey)))) | |
(concat prevKey (rest nextKey)) | |
(empty? other) | |
(concat | |
[(first nextKey)] | |
(if (= 2 (count prevKey)) | |
(drop 1 prevKey) | |
[prevKey]) | |
(rest nextKey)) | |
:else | |
(concat prevKey [nextKey]) | |
)) | |
makeTableKeys | |
(fn [other prevKey nextKey] | |
(let | |
[headKeys | |
(if (coll? (last prevKey)) | |
[] | |
(combineTableKeys other prevKey nextKey)) | |
tailKeys | |
(if (coll? (last prevKey)) | |
(append | |
(butlast prevKey) | |
(combineTableKeys other | |
(last prevKey) nextKey)) | |
[]) | |
] | |
(combineTableKeys other prevKey nextKey))) | |
makeQueueItem | |
(fn [other tableKey] | |
[tableKey other]) | |
genQueueItems | |
(fn [prevKey num other] | |
(if (nil? num) [] | |
(->> | |
(map (partial makeOperation num) operators) | |
(map (partial makeTableKeys other prevKey)) | |
(map (partial makeQueueItem other)) | |
) | |
)) | |
] | |
(loop [[num & other] inputs | |
prevKey '() | |
queue [] | |
table #{}] | |
(let | |
[queueItems | |
(genQueueItems prevKey num other) | |
nextQueue | |
(into queue queueItems) | |
nextTable | |
(into table | |
(->> queueItems | |
(filter (fn [[tableKey otherInputs]] | |
(empty? otherInputs))) | |
(map first) | |
)) | |
] | |
(cond | |
(empty? nextQueue) | |
(->> nextTable | |
(map formatOutput) | |
(filter eval) | |
first | |
) | |
:else | |
(recur | |
(->> nextQueue first second) | |
(->> nextQueue first first) | |
(rest nextQueue) | |
nextTable) | |
)) | |
))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment