Skip to content

Commit 7f2cab4

Browse files
committed
Solve part 2 day 11
1 parent d2d4bbf commit 7f2cab4

File tree

1 file changed

+40
-4
lines changed

1 file changed

+40
-4
lines changed

src/Day11.kt

Lines changed: 40 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
private const val DAY = 11
2+
23
fun main() {
3-
fun part1(octopuses: Array<IntArray>): Int {
4+
fun part1(input: Array<IntArray>): Int {
5+
val octopuses = input.map { it.clone() }.toTypedArray()
46
var flashCount = 0
57
repeat(100) {
68
// increase energy level of all by one
@@ -14,7 +16,6 @@ fun main() {
1416
for (x in octopuses.indices) {
1517
for (y in octopuses[0].indices) {
1618
if (octopuses[x][y] > 9 && !flashedOctopuses[x][y]) {
17-
//octopuses[x][y]++
1819
makeOctopusFlash(octopuses, x, y, flashedOctopuses)
1920
}
2021
}
@@ -32,14 +33,49 @@ fun main() {
3233
return flashCount
3334
}
3435

35-
fun part2(octopuses: Array<IntArray>): Int {
36+
fun part2(input: Array<IntArray>): Int {
37+
val octopuses = input.map { it.clone() }.toTypedArray()
38+
var totalFlashCount = 0
39+
var step = 0
40+
while(true) {
41+
step++
42+
// increase energy level of all by one
43+
for (x in octopuses.indices) {
44+
for (y in octopuses[0].indices) {
45+
octopuses[x][y]++
46+
}
47+
}
48+
// flash all octopuses with energy > 9 plus adjacent ones
49+
val flashedOctopuses: Array<BooleanArray> = Array(10) { BooleanArray(10) }
50+
for (x in octopuses.indices) {
51+
for (y in octopuses[0].indices) {
52+
if (octopuses[x][y] > 9 && !flashedOctopuses[x][y]) {
53+
makeOctopusFlash(octopuses, x, y, flashedOctopuses)
54+
}
55+
}
56+
}
57+
// reset energy level
58+
var flashCountInStep = 0
59+
for (x in octopuses.indices) {
60+
for (y in octopuses[0].indices) {
61+
if (octopuses[x][y] > 9) {
62+
octopuses[x][y] = 0
63+
flashCountInStep++
64+
}
65+
}
66+
}
67+
if (flashCountInStep == 100) {
68+
return step
69+
}
70+
totalFlashCount += flashCountInStep
71+
}
3672
return -1
3773
}
3874

3975
// test if implementation meets criteria from the description, like:
4076
val testInput = readInput(day = DAY, useTestInput = true).toIntArray()
4177
check(part1(testInput) == 1656)
42-
//check(part2(testInput) == 288957)
78+
check(part2(testInput) == 195)
4379

4480
val input = readInput(day = DAY).toIntArray()
4581
println(part1(input))

0 commit comments

Comments
 (0)