-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDay11.kt
66 lines (54 loc) · 2.31 KB
/
Day11.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
import java.io.File
fun main() {
part1("src/main/resources/day11sample.txt")
part1("src/main/resources/day11.txt")
part2("src/main/resources/day11sample.txt")
part2("src/main/resources/day11.txt")
}
typealias Coordinate = Pair<Int, Int>
typealias Grid = List<MutableList<Int>>
private operator fun Grid.get(c: Coordinate) = this[c.first][c.second]
private operator fun Grid.set(c: Coordinate, n: Int) { this[c.first][c.second] = n }
private fun Grid.sequenceOfAll(): List<Coordinate> =
generateSequence(0 to 0) { c ->
if(c.second < this[0].indices.last) { c.first to c.second+1 }
else if (c.first < this.indices.last) { c.first+1 to 0 }
else { null }
}.toList()
private fun Coordinate.getAdjacent(grid: Grid): List<Coordinate> =
listOf(
(this.first to this.second+1), (this.first to this.second-1),
(this.first+1 to this.second), (this.first-1 to this.second),
(this.first+1 to this.second+1), (this.first+1 to this.second-1),
(this.first-1 to this.second+1), (this.first-1 to this.second-1)
).filter {
it.first in (grid.indices) && it.second in (grid[0].indices)
}
private fun Grid.incAll(): Grid = this.apply{ this.sequenceOfAll().forEach { this[it] += 1 } }
private fun Grid.flashAt(c: Coordinate) {
this[c] = 0
c.getAdjacent(this)
.filter { this[it] > 0 } //already flashed
.onEach { this[it] += 1 } //increase energy
.onEach { if(this[it] > 9) { this.flashAt(it) } } //recursively flash
}
private fun Grid.runTurn(): Grid =
this.apply { incAll() }
.apply { sequenceOfAll().forEach { if(this[it] > 9) flashAt(it) } }
private fun Grid.countFlashes(): Int = this.sequenceOfAll().count { this[it] == 0 }
private fun part1(inputFile: String) {
val grid = File(inputFile).readLines()
.map { line -> line.map { c -> c.digitToInt() }.toMutableList() }
generateSequence(grid.runTurn()) { g -> g.runTurn() }
.take(100)
.sumOf { it.countFlashes() }
.apply { println(this) }
}
private fun part2(inputFile: String) {
val grid = File(inputFile).readLines()
.map { line -> line.map { c -> c.digitToInt() }.toMutableList() }
generateSequence(grid) { g -> g.runTurn() }
.takeWhile { it.countFlashes() < 100 }
.count()
.apply { println(this) }
}