6
votes
Day 21: Monkey Math
Today's problem description: https://adventofcode.com/2022/day/21
Please post your solutions in your own top-level comment. Here's a template you can copy-paste into your comment to format it nicely, with the code collapsed by default inside an expandable section with syntax highlighting (you can replace python
with any of the "short names" listed in this page of supported languages):
<details>
<summary>Part 1</summary>
```python
Your code here.
```
</details>
Finally some code I feel I can publish.
Part 1
Racket has promises built-in so I decided to just lazy evaluation. Racket promises are created with
delay
and evaluated usingforce
but there's very neat formlazy
which will go all the way through the chain until everything is evaluated which is ideal for this problem since I don't have to keep checking "are we there yet?" on all those promises.Part 2
I considered re-arranging the expressions so it formed a valid equation for the value of
humn
as in classic algebra. I will come back to this because it sounds like a nice problem. Instead I chose a binary search for the right value ofhumn
.My "clever" part 01 solution won't work nicely because once a promise is forced, it doesn't change which makes it trickier.
Instead I wrote a simple evaluator for the tree and did the binary search for the value of
humn
required. I chose 2128 but in the past I've used a continual doubling range when the limits are unknown. It worked out OK.Using this
evaluate-tree
solves part 1 a little quicker than the promise version but I got to discover thelazy
form.Python
Python