Advertisement
hrabrica

AoC | Day 3 | Part 2

Dec 3rd, 2023
66
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.73 KB | None | 0 0
  1. package year_2023.day_3
  2.  
  3. fun partTwo() {
  4. println("[2023] Day three, part two...")
  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 numberToDigitCoordinatesMapPt2 = 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. CoordinatesPt2(row.indexOf("$number") + digitIdx, idx)
  39. }.also {
  40. row = row.removeNumber(number)
  41. }
  42. }
  43. }
  44.  
  45.  
  46. fun getGearCoordinates(coordinates: List<CoordinatesPt2>): Set<CoordinatesPt2> {
  47. return coordinates.flatMap {
  48. listOf(
  49. CoordinatesPt2(it.x - 1, it.y),
  50. CoordinatesPt2(it.x - 1, it.y - 1),
  51. CoordinatesPt2(it.x - 1, it.y + 1),
  52.  
  53. CoordinatesPt2(it.x, it.y),
  54. CoordinatesPt2(it.x, it.y - 1),
  55. CoordinatesPt2(it.x, it.y + 1),
  56.  
  57. CoordinatesPt2(it.x + 1, it.y),
  58. CoordinatesPt2(it.x + 1, it.y - 1),
  59. CoordinatesPt2(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. .filter { matrix[it.y][it.x] == "*" }
  66. .toSet()
  67. }
  68.  
  69. val mapOfGears = mutableMapOf<CoordinatesPt2, MutableList<Int>>()
  70. numberToDigitCoordinatesMapPt2.forEach { (number, coordinates) ->
  71. val gearCoordinate = getGearCoordinates(coordinates)
  72. gearCoordinate.forEach {
  73. if (mapOfGears[it] == null) {
  74. mapOfGears[it] = mutableListOf()
  75. }
  76.  
  77. mapOfGears[it]!!.add(number)
  78. }
  79. }
  80.  
  81. val sumOfRatios = mapOfGears.filter { it.value.size == 2 }.values.sumOf { it[0] * it[1] }
  82. println(sumOfRatios)
  83. }
  84.  
  85. private data class CoordinatesPt2(val x: Int, val y: Int)
  86.  
  87.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement