Skip to content

Instantly share code, notes, and snippets.

@seanstrom
Created January 28, 2023 16:29
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 seanstrom/f0d1119c24f4d3cb48de33b6ea59425c to your computer and use it in GitHub Desktop.
Save seanstrom/f0d1119c24f4d3cb48de33b6ea59425c to your computer and use it in GitHub Desktop.
Puzzle 87 Solution
(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