-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDay5.kt
55 lines (48 loc) · 2.09 KB
/
Day5.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
import java.io.File
fun main() {
part1("src/main/resources/day5sample.txt")
part1("src/main/resources/day5.txt")
part2("src/main/resources/day5sample.txt")
part2("src/main/resources/day5.txt")
}
typealias Point = Pair<Int, Int>
typealias Line = Pair<Point, Point>
fun Int.progressionTo(i: Int): IntProgression =
if(this > i) { i..this }
else { i downTo this }
fun Line.isHorizontal() = this.first.first == this.second.first
fun Line.isVertical() = this.first.second == this.second.second
fun Line.getHorizontalPoints() = (this.first.second.progressionTo(this.second.second)).map { y -> this.first.first to y }
fun Line.getVerticalPoints() = (this.first.first.progressionTo(this.second.first)).map { x -> x to this.first.second }
fun Line.get45DegreePoints() = getVerticalPoints().map { it.first }.zip(getHorizontalPoints().map { it.second })
fun Line.getAllPoints(allow45degree: Boolean): List<Point> =
when {
this.isHorizontal() -> getHorizontalPoints()
this.isVertical() -> getVerticalPoints()
allow45degree -> get45DegreePoints()
else -> emptyList()
}
private fun part1(inputFile: String) {
val lineRegex = "(\\d+),(\\d+) -> (\\d+),(\\d+)".toRegex()
File(inputFile).readLines().asSequence()
.mapNotNull { input -> lineRegex.find(input)?.destructured?.toList() }
.map { list -> (list[0].toInt() to list[1].toInt()) to (list[2].toInt() to list[3].toInt()) }
.map { line -> line.getAllPoints(false) }
.flatten()
.groupBy { it }
.filter { it.value.size > 1 }
.size
.apply { println(this) }
}
private fun part2(inputFile: String) {
val lineRegex = "(\\d+),(\\d+) -> (\\d+),(\\d+)".toRegex()
File(inputFile).readLines().asSequence()
.mapNotNull { input -> lineRegex.find(input)?.destructured?.toList() }
.map { list -> (list[0].toInt() to list[1].toInt()) to (list[2].toInt() to list[3].toInt()) }
.map { line -> line.getAllPoints(true) }
.flatten()
.groupBy { it }
.filter { it.value.size > 1 }
.size
.apply { println(this) }
}