Skip to content

Commit 8f139eb

Browse files
committed
Day 8 - puzzle 1 - better.
1 parent 8c77bd1 commit 8f139eb

File tree

2 files changed

+63
-1
lines changed

2 files changed

+63
-1
lines changed

src/day_08/puzzle.kt

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
package day_08
2+
3+
import println
4+
import readInput
5+
6+
data class Point(val x: Int, val y: Int) {
7+
operator fun plus(other: Point) = Point(x + other.x, y + other.y)
8+
9+
operator fun times(distance: Int) = Point(x * distance, y * distance)
10+
}
11+
12+
enum class Direction(val move: Point) {
13+
UP(move = Point(0, -1)),
14+
DOWN(move = Point(0, 1)),
15+
LEFT(move = Point(-1, 0)),
16+
RIGHT(move = Point(1, 0))
17+
}
18+
19+
class Grid private constructor(private val trees: List<List<Int>>) {
20+
private val len = trees.size
21+
22+
val visibleCount
23+
get() = (len * 4 - 4) + (1 until (len - 1)).sumOf { y ->
24+
(1 until (len - 1)).count { x -> Point(x, y).visible }
25+
}
26+
27+
private val Point.visible get() = Direction.values().any { visibleTowards(it.move, 1) }
28+
29+
private val Point.value get() = trees[y][x]
30+
31+
private val Point.edge get() = x == 0 || y == 0 || x == len - 1 || y == len - 1
32+
33+
private tailrec fun Point.visibleTowards(move: Point, distance: Int): Boolean {
34+
val neighbour = move * distance + this
35+
36+
return when {
37+
neighbour.value >= value -> false
38+
neighbour.edge -> true
39+
else -> visibleTowards(move, distance + 1)
40+
}
41+
}
42+
43+
companion object {
44+
fun of(lines: List<String>): Grid {
45+
val trees = lines.map { row ->
46+
row.map { it.digitToInt() }
47+
}
48+
49+
return Grid(trees)
50+
}
51+
}
52+
}
53+
54+
fun puzzle1(lines: List<String>) = Grid.of(lines).visibleCount
55+
56+
fun main() {
57+
val testInput = readInput("day_08/input_test")
58+
check(puzzle1(testInput) == 21)
59+
60+
val input = readInput("day_08/input")
61+
puzzle1(input).println()
62+
}

src/day_08_dumb/puzzle.kt

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
package day_08
1+
package day_08_dumb
22

33
// Dumb: no optimization, no cache, no tail recursion.
44

0 commit comments

Comments
 (0)