vbe_elvis

2021 Day8

Dec 8th, 2021 (edited)
122
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Kotlin 2.21 KB | None | 0 0
  1.     val data = """<<INPUT HERE>>""".split("\n").map { it.split(" | ").map { a-> a.split(" ") }}
  2.  
  3.     private val String.sorted: String
  4.         get() = this.toSortedSet().joinToString("")
  5.    
  6.     @Test
  7.     fun `Part 1`() {
  8.         val lengthsToCount = listOf(2,3,4,7)
  9.         println(data[1].sumBy { it.count { segments -> segments.length in lengthsToCount } })
  10.     }
  11.    
  12.     @Test
  13.     fun `Part 2`() {
  14.         val sum = data.map {
  15.             val numbers = extractAllNumbers(it[0].toMutableList())
  16.             it[1].map { segments -> numbers [segments.sorted]}.fold(0) {output, number -> output * 10 + number!! }
  17.         }.sum()
  18.         println("Part 2: $sum")
  19.     }
  20.  
  21.     private fun extractAllNumbers(numbers: MutableList<String>): Map<String, Int> {
  22.         val one = numbers.find { it.length == 2 }!!; numbers -= one
  23.         val four = numbers.find { it.length == 4 }!!; numbers -= four
  24.         val seven = numbers.find { it.length == 3 }!!; numbers -= seven
  25.         val eight = numbers.find { it.length == 7 }!!; numbers -= eight
  26.         val nine = numbers.find { nine ->
  27.             val nineChars = nine.chars().toList(); four.chars().allMatch { nineChars.contains(it) }
  28.         }!!; numbers -= nine
  29.         val zero = numbers.find { zero ->
  30.             val zeroChars = zero.chars().toList(); zero.length == 6 && one.chars().allMatch { zeroChars.contains(it) }
  31.         }!!; numbers -= zero
  32.         val six = numbers.find { it.length == 6 }!!; numbers -= six
  33.         val three = numbers.find { three ->
  34.             val threeChars = three.chars().toList(); one.chars().allMatch { threeChars.contains(it) }
  35.         }!!; numbers -= three
  36.         val five = numbers.find { five ->
  37.             val twoChars = five.chars(); twoChars.allMatch {
  38.             six.chars().toList().contains(it)
  39.         }
  40.         }!!; numbers -= five
  41.         val two = numbers[0]
  42.  
  43.         return listOf(
  44.             one.sorted to 1,
  45.             two.sorted to 2,
  46.             three.sorted to 3,
  47.             four.sorted to 4,
  48.             five.sorted to 5,
  49.             six.sorted to 6,
  50.             seven.sorted to 7,
  51.             eight.sorted to 8,
  52.             nine.sorted to 9,
  53.             zero.sorted to 0
  54.         ).toMap()
  55.     }
Add Comment
Please, Sign In to add comment