Advertisement
hrabrica

AoC | Day 1 | Part 2 (try 2)

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