From 8fdd92b15a1295609bbcf9afa7ed4821820bf803 Mon Sep 17 00:00:00 2001 From: Sven Weidauer Date: Sat, 10 Dec 2022 15:28:16 +0100 Subject: [PATCH] 2022 Day 8 Part 1 --- 2022/.gitignore | 1 + 2022/day8.kt | 83 +++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 84 insertions(+) create mode 100644 2022/day8.kt diff --git a/2022/.gitignore b/2022/.gitignore index 63ff173..708db1e 100644 --- a/2022/.gitignore +++ b/2022/.gitignore @@ -1 +1,2 @@ *.input +*.jar diff --git a/2022/day8.kt b/2022/day8.kt new file mode 100644 index 0000000..a6621f7 --- /dev/null +++ b/2022/day8.kt @@ -0,0 +1,83 @@ +// kotlinc day8.kt -include-runtime -d day8.jar && java -jar day8.jar + +import java.io.File + +class Matrix( + private val data: List +) { + val width = data[0].count() + val height = data.count() + + operator fun get(x: Int, y: Int): Int { + check(x in 0 until width && y in 0 until height) { "Out of bounds" } + + return data[y][x].code - '0'.code + } + + fun column(x: Int): Sequence { + check(x in 0 until width) { "Out of bounds" } + return sequence { + for (y in 0 until height) yield(get(x, y)) + } + } + + fun row(y: Int): Sequence { + check(y in 0 until height) { "Out of bounds" } + return sequence { + for (x in 0 until width) yield(get(x, y)) + } + } + + fun reverseColumn(x: Int): Sequence { + check(x in 0 until width) { "Out of bounds" } + return sequence { + for (y in height - 1 downTo 0) yield(get(x, y)) + } + } + + fun reverseRow(y: Int): Sequence { + check(y in 0 until height) { "Out of bounds" } + return sequence { + for (x in width - 1 downTo 0) yield(get(x, y)) + } + } +} + +fun Sequence.findVisibles(): Set { + var max = -1 + var result = mutableSetOf() + + for ((index,element) in withIndex()) { + if (element > max) { + max = element + result.add(index) + + if (max == 9) break + } + } + + return result +} + +fun main() { + val data = File("day8.input").useLines { lines -> + lines.toList() + } + + val matrix = Matrix(data) + + + val visible = mutableSetOf>() + + for (row in 0 until matrix.height) { + visible.addAll(matrix.row(row).findVisibles().map { it to row }) + visible.addAll(matrix.reverseRow(row).findVisibles().map { matrix.width - 1 - it to row }) + } + + for (col in 0 until matrix.width) { + visible.addAll(matrix.column(col).findVisibles().map { col to it }) + visible.addAll(matrix.reverseColumn(col).findVisibles().map { col to matrix.height - 1 - it }) + } + + println("Part 1: ${visible.count()}") +}