From 19ee5441e52176286cb11a6b85658e0060d03568 Mon Sep 17 00:00:00 2001 From: Matej Focko Date: Sun, 5 Dec 2021 11:23:37 +0100 Subject: [PATCH] day(05): add solution Signed-off-by: Matej Focko --- src/day05/Day05.kt | 72 ++++++++++++++++++++++++++++++++++++++++ src/day05/test_input.txt | 10 ++++++ 2 files changed, 82 insertions(+) create mode 100644 src/day05/Day05.kt create mode 100644 src/day05/test_input.txt diff --git a/src/day05/Day05.kt b/src/day05/Day05.kt new file mode 100644 index 0000000..7b21765 --- /dev/null +++ b/src/day05/Day05.kt @@ -0,0 +1,72 @@ +package day05 + +import readInput + +data class Point(val x: Int, val y: Int) { + operator fun plus(other: Point): Point = Point(x + other.x, y + other.y) + operator fun times(other: Int): Point = Point(other * x, other * y) +} + +data class Vector(val from: Point, val to: Point) { + val horizontal: Boolean + get() = from.y == to.y + + val vertical: Boolean + get() = from.x == to.x + + val horizontalOrVertical: Boolean + get() = horizontal || vertical + + private val xs: Iterable + get() = if (from.x <= to.x) (from.x..to.x) else (to.x..from.x).reversed() + + private val ys: Iterable + get() = if (from.y <= to.y) (from.y..to.y) else (to.y..from.y).reversed() + + val points: Iterable + get() = if (horizontalOrVertical) { + xs.flatMap { x -> ys.map { y -> Point(x, y) } } + } else { + xs.zip(ys).map { (x, y) -> Point(x, y) } + } +} + +fun readPoint(input: String): Point { + val (x, y) = input.split(",").map { it.toInt() } + return Point(x, y) +} + +fun readVector(input: String): Vector { + val (from, to) = input.split(" -> ") + return Vector(readPoint(from), readPoint(to)) +} + +fun part1(input: List): Int { + var points: MutableMap = mutableMapOf() + + input.filter { it.horizontalOrVertical } + .flatMap { it.points } + .forEach { points[it] = 1 + points.getOrDefault(it, 0) } + + return points.count { (_, count) -> count >= 2 } +} + +fun part2(input: List): Int { + var points: MutableMap = mutableMapOf() + + input.flatMap { it.points } + .forEach { points[it] = 1 + points.getOrDefault(it, 0) } + + return points.count { (_, count) -> count >= 2 } +} + +fun main() { + val testInput = readInput(5, "test_input").map { readVector(it) } + val input = readInput(5, "input").map { readVector(it) } + + check(part1(testInput) == 5) + println(part1(input)) + + check(part2(testInput) == 12) + println(part2(input)) +} diff --git a/src/day05/test_input.txt b/src/day05/test_input.txt new file mode 100644 index 0000000..1d4e36d --- /dev/null +++ b/src/day05/test_input.txt @@ -0,0 +1,10 @@ +0,9 -> 5,9 +8,0 -> 0,8 +9,4 -> 3,4 +2,2 -> 2,1 +7,0 -> 7,4 +6,4 -> 2,0 +0,9 -> 2,9 +3,4 -> 1,4 +0,0 -> 8,8 +5,5 -> 8,2 \ No newline at end of file