Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package advent
- class Day6 {
- open class Planet(
- val name : String,
- val orbits : String?
- ) {
- override fun equals(other : Any?) : Boolean {
- if (this === other) return true
- if (other !is Planet) return false
- if (name != other.name) return false
- return true
- }
- override fun hashCode() = name.hashCode()
- override fun toString() = name
- }
- class CenterOfMass : Planet("COM", null)
- companion object {
- fun getInput() : MutableMap<String, Planet> {
- val planets = mutableMapOf<String, Planet>()
- CenterOfMass().also { planets[it.name] = it }
- javaClass
- .getResource("/Day6Input")
- .readText()
- .lines()
- .forEach {
- val parts = it.split(")")
- val planetName = parts[1]
- val orbits = parts[0]
- if (!planets.containsKey(planetName)) {
- planets[planetName] = Planet(planetName, orbits)
- }
- }
- return planets
- }
- fun getPathToCOM(planets : Map<String, Planet>, planet : Planet) : List<Planet> {
- val path = mutableListOf<Planet>()
- var scannedPlanet : Planet? = planet
- while (scannedPlanet != null && scannedPlanet !is CenterOfMass) {
- scannedPlanet = planets[scannedPlanet.orbits]
- path.add(scannedPlanet ?: planets["COM"]!!)
- }
- return path
- }
- fun part1() {
- val planets = getInput()
- var orbits = 0
- for ((_, planet) in planets) {
- orbits += getPathToCOM(planets, planet).size
- }
- println(orbits)
- }
- fun part2() {
- val planets = getInput()
- val yourPath = getPathToCOM(planets, planets["YOU"]!!).reversed()
- val santasPath = getPathToCOM(planets, planets["SAN"]!!).reversed()
- for (i in yourPath.indices) {
- if (yourPath[i] != santasPath[i]) {
- val hops = (yourPath.size - i) + (santasPath.size - i)
- println(hops)
- return
- }
- }
- println("Path not found")
- }
- @JvmStatic
- fun main(args : Array<String>) {
- part1()
- part2()
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement