Skip to content

Commit

Permalink
Add derivative solution to 2022 day 21 part 2
Browse files Browse the repository at this point in the history
  • Loading branch information
sim642 committed Dec 25, 2022
1 parent f978e3d commit f1f52f3
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 0 deletions.
38 changes: 38 additions & 0 deletions src/main/scala/eu/sim642/adventofcode2022/Day21.scala
Original file line number Diff line number Diff line change
Expand Up @@ -170,6 +170,44 @@ object Day21 {
}
}

/**
* Solution, which finds the derivative w.r.t. humn to get the slope
* and then solves linear equation to find humn.
* Assumes expression is linear w.r.t. humn.
*/
object DerivativePart2Solution extends Part2Solution {

override def findHumn(monkeys: Monkeys): Long = {
val humnMonkeys = makeHumnMonkeys(monkeys) + (humn -> Job.Number(0)) // evaluate at 0
val evalName = makeEvalName[BigDecimal](humnMonkeys).andThen(_.get) // always get, because all variables set

def deriveName(name: String): BigDecimal = {
if (name == humn)
1
else
deriveJob(humnMonkeys(name))
}

def deriveJob(job: Job): BigDecimal = job match {
case Job.Number(_) => 0
case Job.Operation(lhs, op, rhs) =>
op match {
case Op.Add => deriveName(lhs) + deriveName(rhs)
case Op.Sub => deriveName(lhs) - deriveName(rhs)
case Op.Mul =>
deriveName(lhs) * evalName(rhs) + evalName(lhs) * deriveName(rhs)
case Op.Div =>
(deriveName(lhs) * evalName(rhs) - evalName(lhs) * deriveName(rhs)) / (evalName(rhs) * evalName(rhs))
}
}

val y0 = evalName(root)
val dy0 = deriveName(root) // derivative at 0
val x0 = y0 / -dy0
x0.setScale(0, BigDecimal.RoundingMode.HALF_UP).longValue
}
}


def parseMonkey(s: String): (String, Job) = s match {
case s"$name: $lhs $opStr $rhs" =>
Expand Down
3 changes: 3 additions & 0 deletions src/test/scala/eu/sim642/adventofcode2022/Day21Test.scala
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ class Day21Test extends Suites(
new InvertPart2SolutionTest,
new BinarySearchPart2SolutionTest,
new LinearPart2SolutionTest,
new DerivativePart2SolutionTest,
)

object Day21Test {
Expand Down Expand Up @@ -58,4 +59,6 @@ object Day21Test {
class BinarySearchPart2SolutionTest extends Part2SolutionTest(BinarySearchPart2Solution)

class LinearPart2SolutionTest extends Part2SolutionTest(LinearPart2Solution)

class DerivativePart2SolutionTest extends Part2SolutionTest(DerivativePart2Solution)
}

0 comments on commit f1f52f3

Please sign in to comment.