1
0
Files
Advent-of-Code/2021/src/main/kotlin/Day05.kt
T
2021-12-05 15:47:12 +01:00

51 lines
1.6 KiB
Kotlin

package be.vandewalleh.aoc.days
import be.vandewalleh.aoc.utils.BaseDay
import be.vandewalleh.aoc.utils.input.Day
@Day
class Day05 : BaseDay() {
data class Point(val x: Int, val y: Int)
private val re = "(\\d+),(\\d+) -> (\\d+),(\\d+)".toRegex()
private fun path(start: Point, end: Point): Sequence<Point> {
val dx = end.x.compareTo(start.x)
val dy = end.y.compareTo(start.y)
return generateSequence(start) {
if (it == end) null
else Point(it.x + dx, it.y + dy)
}
}
override fun part1(): Int {
val visited = HashMap<Point, Int>()
input.lines.value
.map {
re.find(it)!!.destructured.let { (x1, y1, x2, y2) ->
Point(x1.toInt(), y1.toInt()) to Point(x2.toInt(), y2.toInt())
}
}
.filter { (start, end) -> start.x == end.x || start.y == end.y }
.flatMap { (start, end) -> path(start, end) }
.forEach { visited.compute(it) { _, value -> (value ?: 0) + 1 } }
return visited.values.count { it >= 2 }
}
override fun part2(): Int {
val visited = HashMap<Point, Int>()
input.lines.value
.map {
re.find(it)!!.destructured.let { (x1, y1, x2, y2) ->
Point(x1.toInt(), y1.toInt()) to Point(x2.toInt(), y2.toInt())
}
}
.flatMap { (start, end) -> path(start, end) }
.forEach { visited.compute(it) { _, value -> (value ?: 0) + 1 } }
return visited.values.count { it >= 2 }
}
}