todd.ginsberg
12/08/2018, 3:11 PMclass Day08(rawInput: String) {
private val tree: Node = Node.of(rawInput.split(" ").map { it.toInt() }.iterator())
fun solvePart1(): Int =
tree.metadataTotal
fun solvePart2(): Int =
tree.value
private class Node(children: List<Node>, metadata: List<Int>) {
companion object {
fun of(values: Iterator<Int>): Node {
val numChildren: Int = values.next()
val numMetadata: Int = values.next()
val children = (0 until numChildren).map { Node.of(values) }
val metadata = (0 until numMetadata).map { values.next() }.toList()
return Node(children, metadata)
}
}
val metadataTotal: Int =
metadata.sum() + children.sumBy { it.metadataTotal }
val value: Int =
if (children.isEmpty()) metadata.sum()
else metadata.map { children.getSafely(it)?.value ?: 0 }.sum()
private fun List<Node>.getSafely(i: Int): Node? =
if (i > this.size) null
else this[i - 1]
}
}
Thomas Legrand
12/08/2018, 8:54 PMtodd.ginsberg
12/08/2018, 10:11 PMNode.of(...)
that people can use. The of
is "static" in a sense. Another good use for companion objects are for loggers (need only one per type), constants, things of that nature. Does that help you?karelpeeters
12/08/2018, 11:03 PMstatic
-> companion
.todd.ginsberg
12/08/2018, 11:06 PMThomas Legrand
12/09/2018, 10:47 AM