-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDay05HydrothermalVenture.kt
64 lines (53 loc) · 2.05 KB
/
Day05HydrothermalVenture.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
package adventofcode.year2021
import adventofcode.Puzzle
import adventofcode.PuzzleInput
import kotlin.math.max
import kotlin.math.min
class Day05HydrothermalVenture(customInput: PuzzleInput? = null) : Puzzle(customInput) {
private val lines by lazy { input.lines().map { it.split(" -> ").map(Point::invoke) }.map(::Line) }
override fun partOne() =
lines
.filter { it.isHorizontal() || it.isVertical() }
.flatMap(Line::getCoveredPoints)
.groupingBy { it }
.eachCount()
.count { it.value > 1 }
override fun partTwo() =
lines
.flatMap(Line::getCoveredPoints)
.groupingBy { it }
.eachCount()
.count { it.value > 1 }
companion object {
private data class Point(
val x: Int,
val y: Int,
) {
companion object {
operator fun invoke(coordinates: String): Point {
val (x, y) = coordinates.split(",").map(String::toInt)
return Point(x, y)
}
}
}
private data class Line(
val start: Point,
val end: Point,
) {
constructor(points: List<Point>) : this(points.first(), points.last())
fun isHorizontal() = start.y == end.y
fun isVertical() = start.x == end.x
fun getCoveredPoints() =
when {
isHorizontal() -> IntRange(min(start.x, end.x), max(start.x, end.x)).map { Point(it, start.y) }
isVertical() -> IntRange(min(start.y, end.y), max(start.y, end.y)).map { Point(start.x, it) }
else -> {
val left = if (start.x < end.x) start else end
val right = listOf(start, end).minus(left).first()
val gradient = if (left.y < right.y) 1 else -1
(left.x..right.x).map { Point(it, gradient * (it - left.x) + left.y) }
}
}
}
}
}