Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package year_2023.day_3
- fun partTwo() {
- println("[2023] Day three, part two...")
- val input = input()
- val matrix = input.split("\n")
- .filter { it.isNotBlank() }
- .map { it.trim().split("") }
- .map { it.filter { it.isNotBlank() } }
- val specialCharacters = matrix.flatMap { it.map { it } }
- .filter { it.toIntOrNull() == null }
- .filter { it != "." }
- fun removeSpecialChars(row: String): String {
- var cleanRow = row
- specialCharacters.forEach {
- cleanRow = cleanRow.replace(it, ".")
- }
- return cleanRow
- }
- fun String.removeNumber(number: Int): String {
- return this.replaceFirst(
- number.toString(),
- (1..number.toString().length).joinToString("") { "." }
- )
- }
- val numberToDigitCoordinatesMapPt2 = input.split("\n").flatMapIndexed { idx, line ->
- var row = line.trim()
- val numbers = removeSpecialChars(row).split(".").mapNotNull { it.toIntOrNull() }
- numbers.map { number ->
- number to List(number.toString().length) { digitIdx ->
- CoordinatesPt2(row.indexOf("$number") + digitIdx, idx)
- }.also {
- row = row.removeNumber(number)
- }
- }
- }
- fun getGearCoordinates(coordinates: List<CoordinatesPt2>): Set<CoordinatesPt2> {
- return coordinates.flatMap {
- listOf(
- CoordinatesPt2(it.x - 1, it.y),
- CoordinatesPt2(it.x - 1, it.y - 1),
- CoordinatesPt2(it.x - 1, it.y + 1),
- CoordinatesPt2(it.x, it.y),
- CoordinatesPt2(it.x, it.y - 1),
- CoordinatesPt2(it.x, it.y + 1),
- CoordinatesPt2(it.x + 1, it.y),
- CoordinatesPt2(it.x + 1, it.y - 1),
- CoordinatesPt2(it.x + 1, it.y + 1),
- )
- }
- .filter { it.x >= 0 && it.y >= 0 }
- .filter { it.x < matrix.size && it.y < matrix[0].size }
- .filter { it !in coordinates }
- .filter { matrix[it.y][it.x] == "*" }
- .toSet()
- }
- val mapOfGears = mutableMapOf<CoordinatesPt2, MutableList<Int>>()
- numberToDigitCoordinatesMapPt2.forEach { (number, coordinates) ->
- val gearCoordinate = getGearCoordinates(coordinates)
- gearCoordinate.forEach {
- if (mapOfGears[it] == null) {
- mapOfGears[it] = mutableListOf()
- }
- mapOfGears[it]!!.add(number)
- }
- }
- val sumOfRatios = mapOfGears.filter { it.value.size == 2 }.values.sumOf { it[0] * it[1] }
- println(sumOfRatios)
- }
- private data class CoordinatesPt2(val x: Int, val y: Int)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement