Skip to content

Commit

Permalink
Move Overlap Checking to a Separate Function
Browse files Browse the repository at this point in the history
Move the code used to check if the Number/Symbol are overlapping into its own function
  • Loading branch information
GeistInDerSH committed Dec 3, 2023
1 parent a20a1c3 commit d878d62
Showing 1 changed file with 6 additions and 8 deletions.
14 changes: 6 additions & 8 deletions src/main/kotlin/day3/day3.kt
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,7 @@ data class Symbol(val name: Char, val row: Int, val col: Int) {
private val touchingNumbers: MutableSet<Int> = mutableSetOf()

fun addAnyTouchingNumbers(numbers: List<Number>) {
val toAdd = numbers.filter {
(it.row in (row - 1..row + 1)) && (max(it.colStart, col - 1) <= min(it.colEnd, col + 1))
}.map {
it.num
}.toSet()
val toAdd = numbers.filter { hasOverlap(it.row, row, it.colStart, it.colEnd, col) }.map { it.num }.toSet()
touchingNumbers.addAll(toAdd)
}

Expand All @@ -28,14 +24,16 @@ data class Number(val num: Int, val row: Int, val colStart: Int, val colEnd: Int
if (hasTouchingSymbol) {
return
}
hasTouchingSymbol = symbols.any {
(it.row in (row - 1..row + 1)) && (max(colStart, it.col - 1) <= min(colEnd, it.col + 1))
}
hasTouchingSymbol = symbols.any { hasOverlap(it.row, row, colStart, colEnd, it.col) }
}

fun hasTouchingSymbol() = hasTouchingSymbol
}

fun hasOverlap(srcRow: Int, destRow: Int, srcColStart: Int, srcColEnd: Int, destCol: Int): Boolean {
return srcRow in (destRow - 1..destRow + 1) && max(srcColStart, destCol - 1) <= min(srcColEnd, destCol + 1)
}

fun parseInput(fileName: String): Pair<List<Symbol>, List<Number>> {
val lines = fileToStream(fileName).toList()

Expand Down

0 comments on commit d878d62

Please sign in to comment.