Advertisement
hrabrica

AoC | Day 3 | Part 1

Dec 3rd, 2023
95
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.51 KB | None | 0 0
  1. package year_2023.day_3
  2.  
  3. fun partOne() {
  4. println("[2023] Day three, part one...")
  5.  
  6. val input = input()
  7.  
  8. val matrix = input.split("\n")
  9. .filter { it.isNotBlank() }
  10. .map { it.trim().split("") }
  11. .map { it.filter { it.isNotBlank() } }
  12.  
  13. val specialCharacters = matrix.flatMap { it.map { it } }
  14. .filter { it.toIntOrNull() == null }
  15. .filter { it != "." }
  16.  
  17. fun removeSpecialChars(row: String): String {
  18. var cleanRow = row
  19. specialCharacters.forEach {
  20. cleanRow = cleanRow.replace(it, ".")
  21. }
  22. return cleanRow
  23. }
  24.  
  25. fun String.removeNumber(number: Int): String {
  26. return this.replaceFirst(
  27. number.toString(),
  28. (1..number.toString().length).joinToString("") { "." }
  29. )
  30. }
  31.  
  32.  
  33. val numberToDigitCoordinatesMap = input.split("\n").flatMapIndexed { idx, line ->
  34. var row = line.trim()
  35. val numbers = removeSpecialChars(row).split(".").mapNotNull { it.toIntOrNull() }
  36. numbers.map { number ->
  37. number to List(number.toString().length) { digitIdx ->
  38. Coordinates(row.indexOf("$number") + digitIdx, idx)
  39. }.also {
  40. row = row.removeNumber(number)
  41. }
  42. }
  43. }
  44.  
  45.  
  46. fun numberIsPartNumber(coordinates: List<Coordinates>): Boolean {
  47. val coordinatesAround = coordinates.flatMap {
  48. listOf(
  49. Coordinates(it.x - 1, it.y),
  50. Coordinates(it.x - 1, it.y - 1),
  51. Coordinates(it.x - 1, it.y + 1),
  52.  
  53. Coordinates(it.x, it.y),
  54. Coordinates(it.x, it.y - 1),
  55. Coordinates(it.x, it.y + 1),
  56.  
  57. Coordinates(it.x + 1, it.y),
  58. Coordinates(it.x + 1, it.y - 1),
  59. Coordinates(it.x + 1, it.y + 1),
  60. )
  61. }
  62. .filter { it.x >= 0 && it.y >= 0 }
  63. .filter { it.x < matrix.size && it.y < matrix[0].size }
  64. .filter { it !in coordinates }
  65. .toSet()
  66.  
  67. return coordinatesAround.any {
  68. val point = matrix[it.y][it.x]
  69. point.toIntOrNull() == null && point != "."
  70. }
  71. }
  72.  
  73. var sumOfPartNumbers = 0
  74. numberToDigitCoordinatesMap.forEach { (number, coordinates) ->
  75. if (numberIsPartNumber(coordinates)) {
  76. sumOfPartNumbers += number
  77. }
  78. }
  79.  
  80. println(sumOfPartNumbers)
  81. }
  82.  
  83. private data class Coordinates(val x: Int, val y: Int)
  84.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement