Day05 2021
This commit is contained in:
@@ -0,0 +1,50 @@
|
||||
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 }
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user