AoC 2022 D21: Monkey Math
| Problem statement | Source code | Tags: Mathematics
← Previous Back to AoC Index Next →
Part 1
There are two kinds of monkeys: those that yell a number, and those that yell an expression. Therefore I parse the input as:
A Const monkey just returns a number, while an Operation monkey is left op right. Now I can recursively evaluate:
Where combineRes just does the math:
Part 2
Now the value of humn is unknown, so basically we've turned a constant expression into a symbolic equation. For example, the example in part 1 looked like:
Which represents the equation:
Giving the answer of 152. Now with humn unknown, we have:
And we need to solve for . This is just a matter of simplifying both sides and then isolating . To represent this equation, we need a new monkey type, Unknown, to stand in for humn:
Now EvalRes is no longer just a number, but can also be an expression. I'm assuming that the expression is always linear in humn, so I represent it as a * humn + b:
combineRes now handles the algebra of two linear expressions, but nothing more than that. This means that multiplication only works if one of the expressions is a constant, and division only works if the denominator is a constant.
Now we can evaluate the left and right sides of the equation, and then solve for humn. The simplified equation looks like:
(Well, in reality, only appears on one side, but it doesn't hurt to be a bit more general.) The solution is just: