-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDay21.kt
47 lines (39 loc) · 1.49 KB
/
Day21.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
package aoc.years.year2022
import aoc.Day
import org.mariuszgromada.math.mxparser.Expression
@Year2022
class Day21 : Day() {
override fun solvePart1(input: List<String>): Any {
return input
.map { it.split(": ") }
.associate { (name, expr) -> Pair(name, expr) }
.toMutableMap()
.getRootExpressionResult()
}
override fun solvePart2(input: List<String>): Any {
return input
.map { it.split(": ") }
.associate { (name, expr) -> Pair(name, expr) }
.toMutableMap()
.getHumanExpressionForRootExpressionToBeEqual()
}
}
private fun MutableMap<String, String>.getRootExpressionResult(): Long {
this.flattenRootExpression()
return Expression(this["root"]).calculate().toLong()
}
private fun MutableMap<String, String>.getHumanExpressionForRootExpressionToBeEqual(): Long {
this["humn"] = "?"
this["root"] = this["root"]!!.replace("[+\\-*/]".toRegex(), "-")
this.flattenRootExpression()
this["root"] = this["root"]!!.replace("?", "x")
return Expression("solve(${this["root"]}, x, -9999999999999, 9999999999999)").calculate().toLong()
}
private fun MutableMap<String, String>.flattenRootExpression() {
while (this["root"]!!.contains("[a-zA-Z]".toRegex())) {
this["root"] = this["root"]!!
.split(" ")
.map { if (it.contains("[a-zA-Z]".toRegex())) return@map "( ${this[it]} )" else return@map it }
.joinToString(" ")
}
}