Advertisement
Guest User

Untitled

a guest
Dec 8th, 2019
104
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Kotlin 1.50 KB | None | 0 0
  1. class Day6 {
  2.  
  3.     companion object {
  4.         const val COM = "COM"
  5.         const val YOU = "YOU"
  6.         const val SANTA = "SAN"
  7.     }
  8.  
  9.     /**
  10.      * PART #1
  11.      */
  12.     fun doPart1(input: Array<String>): Int? {
  13.         val dataMap = buildMap(input)
  14.         return dataMap.map { countOrbits(it.value, dataMap) }.sum()
  15.     }
  16.  
  17.     private fun buildMap(input: Array<String>) = input.map { it.split(')') }.associateBy({ it[1] }, { it[0] })
  18.  
  19.     private tailrec fun countOrbits(value: String, dataMap: Map<String, String>, orbits: Int = 1): Int {
  20.         if (value == COM) return orbits
  21.         return countOrbits(dataMap.getValue(value), dataMap, orbits + 1)
  22.     }
  23.  
  24.     /**
  25.      * PART #2
  26.      */
  27.     fun doPart2(input: Array<String>): Int? {
  28.         val dataMap = buildMap(input)
  29.         return listOf(YOU, SANTA)
  30.             .map { buildPath(dataMap.getValue(it), dataMap) }
  31.             .zipWithNext(function()).first().split(',').count()
  32.     }
  33.  
  34.     private fun function(): (a: String, b: String) -> String {
  35.         return { you, santa ->
  36.             val commonPrefix = you.zip(santa).takeWhile { it.first == it.second }.map { it.first }.joinToString("")
  37.             listOf(you, santa).joinToString(",") { it.removePrefix(commonPrefix) }
  38.         }
  39.     }
  40.  
  41.     private tailrec fun buildPath(value: String, dataMap: Map<String, String>, way: String = ""): String {
  42.         if (value == COM) return way.dropLast(1)
  43.         return buildPath(dataMap.getValue(value), dataMap, "$value,$way")
  44.     }
  45.  
  46. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement