Day 4 Part 1
This commit is contained in:
parent
b37bdc8b3e
commit
e1f0159403
4 changed files with 243 additions and 0 deletions
66
2024/src/main/kotlin/Grid.kt
Normal file
66
2024/src/main/kotlin/Grid.kt
Normal file
|
@ -0,0 +1,66 @@
|
|||
class Grid(val rows: List<String>) {
|
||||
val width = rows.firstOrNull()?.count() ?: 0
|
||||
val height get() = rows.count()
|
||||
|
||||
init {
|
||||
assert(rows.all { it.length == width })
|
||||
}
|
||||
|
||||
companion object {
|
||||
fun read(name: String): Grid = Grid(readInput(name).toList())
|
||||
}
|
||||
|
||||
fun chars(x: Int, y: Int, dx: Int, dy: Int) = Line(x, y, dx, dy)
|
||||
|
||||
inner class Line(val x: Int, val y: Int, val dx: Int, val dy: Int) : Sequence<Char> {
|
||||
override fun iterator(): Iterator<Char> = iterator {
|
||||
if (dx == 1 && dy == 0) {
|
||||
yieldAll(rows[y].substring(startIndex = x).asSequence())
|
||||
} else {
|
||||
|
||||
var x = x
|
||||
var y = y
|
||||
|
||||
while (x in 0..<width && y in 0..<height) {
|
||||
yield(get(x, y))
|
||||
x += dx
|
||||
y += dy
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun rows(): Sequence<Line> = sequence {
|
||||
for (y in 0..<height) {
|
||||
yield(chars(0, y, 1, 0))
|
||||
}
|
||||
}
|
||||
|
||||
fun columns(): Sequence<Line> = sequence {
|
||||
for (x in 0..<width) {
|
||||
yield(chars(x, 0, 0, 1))
|
||||
}
|
||||
}
|
||||
|
||||
fun diagonals(): Sequence<Line> = sequence {
|
||||
for (x in 0..<width) {
|
||||
yield(chars(x, 0, 1, 1))
|
||||
if (x > 0) {
|
||||
yield(chars(x, 0, -1, 1))
|
||||
}
|
||||
}
|
||||
for (y in 1..<height) {
|
||||
yield(chars(0, y, 1, 1))
|
||||
yield(chars(width - 1, y, -1, 1))
|
||||
}
|
||||
}
|
||||
|
||||
fun all(): Sequence<Line> = sequence {
|
||||
yieldAll(rows())
|
||||
yieldAll(columns())
|
||||
yieldAll(diagonals())
|
||||
}
|
||||
|
||||
fun get(x: Int, y: Int): Char = rows[y][x]
|
||||
|
||||
}
|
27
2024/src/main/kotlin/day4.kt
Normal file
27
2024/src/main/kotlin/day4.kt
Normal file
|
@ -0,0 +1,27 @@
|
|||
fun main() {
|
||||
val grid = Grid.read("day4.txt")
|
||||
|
||||
val part1 = grid.all().fold(0) { acc, line ->
|
||||
val string = line.joinToString(separator = "")
|
||||
println(string)
|
||||
|
||||
acc + string.countSubstring("XMAS") + string.countSubstring("SAMX")
|
||||
}
|
||||
|
||||
println("Part 1: $part1")
|
||||
}
|
||||
|
||||
fun String.countSubstring(substring: String): Int {
|
||||
var start = 0
|
||||
var count = 0
|
||||
|
||||
while (true) {
|
||||
val next = indexOf(substring, start)
|
||||
if (next == -1) break
|
||||
|
||||
count++
|
||||
start = next + substring.length
|
||||
}
|
||||
|
||||
return count
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue