This commit is contained in:
2018-12-08 14:33:15 +01:00
parent 0e7b53b651
commit 6a5f28117d
2 changed files with 78 additions and 0 deletions

View File

@@ -0,0 +1,77 @@
package com.basdado.adventofcode
import java.util.stream.Stream
fun main() {
val day = Day8()
day.puzzle1()
day.puzzle2()
}
class Day8 {
fun puzzle1() {
val root = parseInput()
println(flatMap(root) { it.metadata.stream() }.mapToInt{ it }.sum())
}
fun puzzle2() {
val root = parseInput()
println(findValue(root))
}
private fun parseInput(): Node {
val input = lines("/day/8/input.txt")
.findFirst().get()
.split(Regex("""\s+"""))
.map { it.toInt() }
.toIntArray()
return parse(input)
}
fun parse(arr: IntArray, startIndex: Int = 0): Node {
var index = startIndex;
val nodeCount = arr[index++]
val metadataCount = arr[index++]
var children = mutableListOf<Node>()
for (i in 0 until nodeCount) {
val newChild = parse(arr, index)
index = newChild.endIndex
children.add(newChild)
}
val metadata = arr.copyOfRange(index, index + metadataCount).toList()
index += metadataCount
return Node(children, metadata, index)
}
fun <T> flatMap(node: Node, mapping: Function1<Node, Stream<T>>): Stream<T> {
var res = mapping.invoke(node)
for (child in node.children) {
res = Stream.concat(res, flatMap(child, mapping))
}
return res
}
fun findValue(node: Node): Int {
if (node.children.isEmpty()) {
return node.metadata.toIntArray().sum()
} else {
var sum = 0
for (index in node.metadata) {
if (index > 0 && index <= node.children.size) {
sum += findValue(node.children[index - 1])
}
}
return sum
}
}
data class Node (val children: List<Node>, val metadata: List<Int>, val endIndex: Int)
}

File diff suppressed because one or more lines are too long