Day 6 (finally got time)

This commit is contained in:
2019-12-08 23:52:12 +01:00
parent 23d5f0233f
commit 494c826a66
5 changed files with 1374 additions and 1 deletions

View File

@@ -165,5 +165,5 @@ object Day5 {
data class OperationResult(val moveToNextInstruction: Boolean = true, val output: Int? = null)
val VOID = OperationResult()
private val VOID = OperationResult()
}

View File

@@ -0,0 +1,77 @@
package com.basdado.adventofcode.day6
import com.basdado.adventofcode.lines
const val DAY6_INPUT_PATH = "/day/6/input.txt"
fun main() {
Day6.puzzle1()
Day6.puzzle2()
}
object Day6 {
fun puzzle1() {
// orbits is a map from names to the objects they are orbiting
val orbits = loadOrbits()
val cache = mutableMapOf<String, Int>()
println(orbits.keys.stream()
// .peek{ println("${calculateOrbitCount(it, orbits, cache)} orbit in $it")}
.mapToInt { calculateOrbitCount(it, orbits, cache) }
.sum())
}
fun puzzle2() {
val orbits = loadOrbits()
val youToRoot = pathToRoot("YOU", orbits).reversed()
val sanToRoot = pathToRoot("SAN", orbits).reversed()
println(youToRoot)
println(sanToRoot)
val overlapLength = youToRoot.indexOfLast { sanToRoot.contains(it) } + 1
println((youToRoot.size - 1 - overlapLength) + (sanToRoot.size - 1 - overlapLength))
}
private fun loadOrbits(): Map<String, String> {
val orbits = mutableMapOf<String, String>()
lines(DAY6_INPUT_PATH)
.forEach {
val split = it.indexOf(")")
val o1 = it.substring(0, split)
val o2 = it.substring(split + 1)
orbits[o2] = o1
}
return orbits
}
private fun calculateOrbitCount(o: String, orbits: Map<String, String>, cache: MutableMap<String, Int>): Int {
val parent = orbits[o]
val res = if (parent == null) {
0
} else {
1 + (cache[parent] ?: calculateOrbitCount(parent, orbits, cache))
}
cache[o] = res
return res
}
private fun pathToRoot(source: String, orbits: Map<String, String>): List<String> {
val parent = orbits[source]
return if (parent == null) {
listOf(source)
} else {
listOf(source) + pathToRoot(parent, orbits)
}
}
data class SpaceObject (
val name: String,
val parent: SpaceObject? = null
)
}

View File

@@ -0,0 +1,11 @@
COM)B
B)C
C)D
D)E
E)F
B)G
G)H
D)I
E)J
J)K
K)L

View File

@@ -0,0 +1,13 @@
COM)B
B)C
C)D
D)E
E)F
B)G
G)H
D)I
E)J
J)K
K)L
K)YOU
I)SAN

File diff suppressed because it is too large Load Diff