Skip to content

Commit dfd7123

Browse files
committed
add solution for day 5
1 parent f5b95ca commit dfd7123

File tree

5 files changed

+587
-0
lines changed

5 files changed

+587
-0
lines changed

src/main/kotlin/advent2021/Day05.kt

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
package advent2021
2+
3+
import Resources
4+
import advent2021.shared.Point2d
5+
6+
class Day05(input: List<String>) {
7+
8+
private val instructions = input.map { parseRow(it) }
9+
10+
fun solvePart1(): Int =
11+
solve { it.first sharesAxisWith it.second }
12+
13+
fun solvePart2(): Int =
14+
solve { true }
15+
16+
private fun solve(lineFilter: (Pair<Point2d, Point2d>) -> Boolean) =
17+
instructions
18+
.filter { lineFilter(it) }
19+
.flatMap { it.first lineTo it.second }
20+
.groupingBy { it }
21+
.eachCount()
22+
.count { it.value > 1 }
23+
24+
private fun parseRow(input: String): Pair<Point2d, Point2d> =
25+
Pair(
26+
input.substringBefore(" ").split(",").map { it.toInt() }.let { Point2d(it.first(), it.last()) },
27+
input.substringAfterLast(" ").split(",").map { it.toInt() }.let { Point2d(it.first(), it.last()) }
28+
)
29+
}
30+
31+
fun main() {
32+
val input = Resources.resourceAsListOfString("advent2021/day05.txt")
33+
val day = Day05(input = input)
34+
println("Part 1: ${day.solvePart1()}")
35+
println("Part 2: ${day.solvePart2()}")
36+
}
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
package advent2021.shared
2+
3+
import kotlin.math.absoluteValue
4+
import kotlin.math.sign
5+
6+
data class Point2d(val x: Int, val y: Int) {
7+
8+
infix fun sharesAxisWith(that: Point2d): Boolean =
9+
x == that.x || y == that.y
10+
11+
infix fun lineTo(that: Point2d): List<Point2d> {
12+
val xDelta = (that.x - x).sign
13+
val yDelta = (that.y - y).sign
14+
15+
val steps = maxOf((x - that.x).absoluteValue, (y - that.y).absoluteValue)
16+
17+
return (1 .. steps).scan(this) { last, _ -> Point2d(last.x + xDelta, last.y + yDelta) }
18+
}
19+
}

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy