Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Day6 {
- companion object {
- const val COM = "COM"
- const val YOU = "YOU"
- const val SANTA = "SAN"
- }
- /**
- * PART #1
- */
- fun doPart1(input: Array<String>): Int? {
- val dataMap = buildMap(input)
- return dataMap.map { countOrbits(it.value, dataMap) }.sum()
- }
- private fun buildMap(input: Array<String>) = input.map { it.split(')') }.associateBy({ it[1] }, { it[0] })
- private tailrec fun countOrbits(value: String, dataMap: Map<String, String>, orbits: Int = 1): Int {
- if (value == COM) return orbits
- return countOrbits(dataMap.getValue(value), dataMap, orbits + 1)
- }
- /**
- * PART #2
- */
- fun doPart2(input: Array<String>): Int? {
- val dataMap = buildMap(input)
- return listOf(YOU, SANTA)
- .map { buildPath(dataMap.getValue(it), dataMap) }
- .zipWithNext(function()).first().split(',').count()
- }
- private fun function(): (a: String, b: String) -> String {
- return { you, santa ->
- val commonPrefix = you.zip(santa).takeWhile { it.first == it.second }.map { it.first }.joinToString("")
- listOf(you, santa).joinToString(",") { it.removePrefix(commonPrefix) }
- }
- }
- private tailrec fun buildPath(value: String, dataMap: Map<String, String>, way: String = ""): String {
- if (value == COM) return way.dropLast(1)
- return buildPath(dataMap.getValue(value), dataMap, "$value,$way")
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement