Kroppeb
12/18/2020, 5:32 AMMichael de Kaste
12/18/2020, 8:06 AMobject Day18 : AdventOfCode() {
val parsed = input.lines().map { it.replace(" ", "") }
override fun part1() = parsed.map(::solveEquation).sum()
data class Index(var value: Int)
private fun solveEquation(input: String, index: Index = Index(0)) : Long {
var sum = 0L
var opIsPlus = true
while (index.value < input.length) {
when (val c = input[index.value++]) {
in '0'..'9' -> sum = applyOp(sum, opIsPlus, c - '0' - 0L)
'*' -> opIsPlus = false
'+' -> opIsPlus = true
'(' -> sum = applyOp(sum, opIsPlus, solveEquation(input, index))
')' -> return sum
}
}
return sum
}
private fun applyOp(sum: Long, opIsPlus: Boolean, other: Long) = if(opIsPlus) sum + other else sum * other
override fun part2() = parsed.map(::solvePart2).sum()
private fun solvePart2(input: String) : Long {
var s = input
while(true){
val (o, c) = findOpenClosed(s) ?: return solvePart(s)
s = s.substring(0, o) + solvePart(s.substring(o + 1, c)) + s.substring(c + 1)
}
}
private fun findOpenClosed(input: String) : Pair<Int, Int>? {
var openIndex = 0
for(i in input.indices){
when(input[i]){
'(' -> openIndex = i
')' -> return openIndex to i
}
}
return null
}
private fun solvePart(input: String) = input.split('*')
.map { it.split('+').sumOf(String::toLong) }
.reduce { acc, i -> acc * i }
}
ephemient
12/18/2020, 12:51 PMNir
12/18/2020, 5:06 PMNir
12/18/2020, 5:06 PMNir
12/18/2020, 5:07 PMNir
12/18/2020, 5:07 PMephemient
12/18/2020, 5:28 PMephemient
12/18/2020, 5:28 PMephemient
12/18/2020, 5:30 PMNir
12/18/2020, 5:36 PMNir
12/18/2020, 5:36 PMNir
12/18/2020, 5:37 PMNir
12/18/2020, 5:37 PMephemient
12/18/2020, 5:58 PMephemient
12/18/2020, 6:02 PMNir
12/18/2020, 6:06 PMtodd.ginsberg
12/18/2020, 6:31 PMtodd.ginsberg
12/18/2020, 6:31 PMephemient
12/18/2020, 6:47 PMIterable<T>.sumOf(selector: (T) -> Long)
in the standard libraryephemient
12/18/2020, 6:48 PMephemient
12/18/2020, 6:51 PMMichael de Kaste
12/18/2020, 6:52 PMMichael de Kaste
12/18/2020, 6:53 PMMichael de Kaste
12/18/2020, 6:53 PMNir
12/18/2020, 6:55 PMNir
12/18/2020, 6:55 PMephemient
12/18/2020, 6:58 PMNir
12/18/2020, 7:02 PMephemient
12/18/2020, 7:03 PMephemient
12/18/2020, 7:04 PMKroppeb
12/18/2020, 7:04 PMKroppeb
12/18/2020, 7:05 PMephemient
12/18/2020, 7:06 PMtodd.ginsberg
12/18/2020, 9:00 PMtodd.ginsberg
12/18/2020, 9:42 PMLuke
12/18/2020, 9:56 PMtodd.ginsberg
12/18/2020, 10:07 PMbjonnh
12/18/2020, 11:25 PMbjonnh
12/18/2020, 11:27 PMbjonnh
12/18/2020, 11:28 PMbjonnh
12/18/2020, 11:29 PMbjonnh
12/18/2020, 11:37 PMNir
12/18/2020, 11:38 PMNir
12/18/2020, 11:39 PMNir
12/18/2020, 11:39 PMbjonnh
12/18/2020, 11:39 PMbjonnh
12/18/2020, 11:39 PMbjonnh
12/18/2020, 11:39 PMNir
12/18/2020, 11:39 PMNir
12/18/2020, 11:39 PMNir
12/18/2020, 11:40 PMNir
12/18/2020, 11:41 PMbjonnh
12/19/2020, 12:07 AMbjonnh
12/19/2020, 12:07 AMbjonnh
12/19/2020, 12:07 AMbjonnh
12/19/2020, 12:07 AM