Skip to content

Commit 3fa03c0

Browse files
committed
Solution 2018-08 (Memory Maneuver)
1 parent 4add4e9 commit 3fa03c0

File tree

2 files changed

+70
-0
lines changed

2 files changed

+70
-0
lines changed
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
package de.ronny_h.aoc.year2018.day08
2+
3+
import de.ronny_h.aoc.AdventOfCode
4+
5+
fun main() = MemoryManeuver().run(45618, 22306)
6+
7+
class MemoryManeuver : AdventOfCode<Int>(2018, 8) {
8+
override fun part1(input: List<String>): Int = input.parseTreeNodes().metadataSum()
9+
override fun part2(input: List<String>): Int = input.parseTreeNodes().value()
10+
}
11+
12+
data class Node(private val meta: List<Int>, private val children: List<Node>) {
13+
fun metadataSum(): Int = meta.sum() + children.sumOf(Node::metadataSum)
14+
fun value(): Int = if (children.isEmpty()) {
15+
meta.sum()
16+
} else {
17+
meta.filter { it in 1..children.size }
18+
.sumOf { children[it - 1].value() }
19+
}
20+
}
21+
22+
fun List<String>.parseTreeNodes(): Node {
23+
val numbers = single().split(" ").map(String::toInt)
24+
25+
fun parseSubtree(numbers: List<Int>): Pair<Node, Int> {
26+
val childCount = numbers[0]
27+
val metaCount = numbers[1]
28+
29+
var offset = 2
30+
val children = mutableListOf<Node>()
31+
repeat(childCount) {
32+
val (child, length) = parseSubtree(numbers.subList(offset, numbers.lastIndex))
33+
offset += length
34+
children += child
35+
}
36+
return Node(numbers.subList(offset, offset + metaCount), children) to metaCount + offset
37+
}
38+
39+
return parseSubtree(numbers).first
40+
}
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
package de.ronny_h.aoc.year2018.day08
2+
3+
import io.kotest.core.spec.style.StringSpec
4+
import io.kotest.matchers.shouldBe
5+
6+
class MemoryManeuverTest : StringSpec({
7+
8+
val input = listOf("2 3 0 3 10 11 12 1 1 0 1 99 2 1 1 2")
9+
10+
"tree nodes can be parsed" {
11+
input.parseTreeNodes() shouldBe Node(
12+
listOf(1, 1, 2), listOf(
13+
Node(listOf(10, 11, 12), emptyList()),
14+
Node(
15+
listOf(2), listOf(
16+
Node(listOf(99), emptyList())
17+
)
18+
)
19+
)
20+
)
21+
}
22+
23+
"part 1: the sum of all metadata entries" {
24+
MemoryManeuver().part1(input) shouldBe 138
25+
}
26+
27+
"part 2: the value dependent on having child nodes" {
28+
MemoryManeuver().part2(input) shouldBe 66
29+
}
30+
})

0 commit comments

Comments
 (0)