Advertisement
hrabrica

AoC | Day 1 | Part 2

Dec 1st, 2023
297
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.45 KB | None | 0 0
  1. package year_2023.day_1
  2. fun partTwo() {
  3. println("[2023] Day one, part two...")
  4.  
  5. val validNumbers = mapOf(
  6. "one" to 1,
  7. "two" to 2,
  8. "three" to 3,
  9. "four" to 4,
  10. "five" to 5,
  11. "six" to 6,
  12. "seven" to 7,
  13. "eight" to 8,
  14. "nine" to 9
  15. )
  16.  
  17. val numbers = input().split("\n")
  18. .map { line ->
  19. val firstDigit = line.firstOrNull { it.isDigit() }?.let { it.toString() to line.indexOf(it) }
  20. val firstWord = validNumbers.keys.mapNotNull { key ->
  21. if (line.contains(key)) {
  22. return@mapNotNull validNumbers[key]!!.toString() to line.indexOf(key)
  23. }
  24.  
  25. null
  26. }.minByOrNull { it.second }
  27.  
  28. val lastDigit = line.lastOrNull { it.isDigit() }?.let { it.toString() to line.lastIndexOf(it) }
  29. val lastWord = validNumbers.keys.mapNotNull { key ->
  30. if (line.contains(key)) {
  31. return@mapNotNull validNumbers[key]!!.toString() to line.lastIndexOf(key)
  32. }
  33.  
  34. null
  35. }.maxByOrNull { it.second }
  36.  
  37. val first = listOf(firstDigit, firstWord).minBy { it?.second ?: Int.MAX_VALUE }!!.first
  38. val last = listOf(lastDigit, lastWord).maxBy { it?.second ?: Int.MIN_VALUE }!!.first
  39.  
  40. "$first$last".toInt()
  41. }
  42.  
  43. val sum = numbers.sum()
  44. println(sum)
  45. }
  46.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement