Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package year_2023.day_3
- fun partOne() {
- println("[2023] Day three, part one...")
- 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 numberToDigitCoordinatesMap = 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 ->
- Coordinates(row.indexOf("$number") + digitIdx, idx)
- }.also {
- row = row.removeNumber(number)
- }
- }
- }
- fun numberIsPartNumber(coordinates: List<Coordinates>): Boolean {
- val coordinatesAround = coordinates.flatMap {
- listOf(
- Coordinates(it.x - 1, it.y),
- Coordinates(it.x - 1, it.y - 1),
- Coordinates(it.x - 1, it.y + 1),
- Coordinates(it.x, it.y),
- Coordinates(it.x, it.y - 1),
- Coordinates(it.x, it.y + 1),
- Coordinates(it.x + 1, it.y),
- Coordinates(it.x + 1, it.y - 1),
- Coordinates(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 }
- .toSet()
- return coordinatesAround.any {
- val point = matrix[it.y][it.x]
- point.toIntOrNull() == null && point != "."
- }
- }
- var sumOfPartNumbers = 0
- numberToDigitCoordinatesMap.forEach { (number, coordinates) ->
- if (numberIsPartNumber(coordinates)) {
- sumOfPartNumbers += number
- }
- }
- println(sumOfPartNumbers)
- }
- private data class Coordinates(val x: Int, val y: Int)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement