From 687cba82ddcb83855a5c5dd869ba81052f63ec4b Mon Sep 17 00:00:00 2001 From: kageru Date: Fri, 6 Dec 2019 11:44:33 +0100 Subject: [PATCH] Simplify D6P2 Kotlin further --- 2019/06/day06.kt | 15 ++------------- 1 file changed, 2 insertions(+), 13 deletions(-) diff --git a/2019/06/day06.kt b/2019/06/day06.kt index 48d4ad6..1309b4d 100644 --- a/2019/06/day06.kt +++ b/2019/06/day06.kt @@ -1,12 +1,12 @@ fun main() { val input = generateSequence(::readLine).map { it.split(")") }.toList() val parentToChildren = input.groupBy { it[0] }.mapValues { it.value.map { it[1] } } - val childToParent = input.associateBy { it[1] }.mapValues { it.value[0] } val rootNode = (parentToChildren.keys - parentToChildren.values.flatten().toSet()).first() println("Part 1: ${countOrbiters(parentToChildren, rootNode, 0)}") + val childToParent = input.associateBy { it[1] }.mapValues { it.value[0] } val santaParents = getParents(childToParent, "SAN") val myParents = getParents(childToParent, "YOU") - val commonParent = firstCommon(santaParents, myParents) + val commonParent = santaParents.first { it in myParents } println("Part 2: ${santaParents.indexOf(commonParent) + myParents.indexOf(commonParent)}") } @@ -15,14 +15,3 @@ fun countOrbiters(graph: Map>, key: T, acc: Int): Int = fun getParents(graph: Map, key: T): List = graph[key]?.let { curr -> listOf(curr) + getParents(graph, curr) } ?: emptyList() - -fun firstCommon(first: List, second: List): T { - val seen = mutableSetOf() - for (i in 0..first.size) { - if (first[i] in seen) return first[i] - seen.add(first[i]) - if (second[i] in seen) return second[i] - seen.add(second[i]) - } - error("should be unreachable") -}