-
Notifications
You must be signed in to change notification settings - Fork 0
/
Day04.kt
129 lines (96 loc) · 3 KB
/
Day04.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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
package y2021
import general.Day
import java.util.*
object Day04 : Day() {
override val name = "Giant Squid"
class Board {
val data = Array(5) { Array(5) { 0 } }
@Suppress("ControlFlowWithEmptyBody")
fun read(input: List<String>, startIndex: Int): Int {
var row = 0
var index = startIndex
if (index >= input.size) return -1
while (input[index].isBlank())
if (++index >= input.size) return -1
while (true) {
if (index >= input.size) break
val line = input[index]
if (line.isBlank()) break
data[row] = line
.split(" ")
.filter { it.isNotBlank() }
.map { it.toInt() }
.toTypedArray()
row += 1
index += 1
}
if (row == 0) return -1
return index
}
fun draw(number: Int) {
for (i in 0..4) for (j in 0..4)
if (data[i][j] == number)
data[i][j] = -1
}
fun hasWon(): Boolean {
column@for (i in 0..4) {
for (j in 0..4) if (data[i][j] != -1) continue@column
return true
}
row@for (i in 0..4) {
for (j in 0..4) if (data[j][i] != -1) continue@row
return true
}
return false
}
fun sum(): Int {
var sum = 0
for (i in 0..4) for (j in 0..4)
if (data[i][j] >= 0)
sum += data[i][j]
return sum
}
}
private fun readInput(): Pair<List<Int>, LinkedList<Board>> {
val input = INPUT.readLines()
val numbers = input[0].split(",").map { it.toInt() }
val boards = LinkedList<Board>()
var index = 2
while (index < input.size) {
val board = Board()
val end = board.read(input, index)
if (end == -1) break
boards += board
index = end
}
return Pair(numbers, boards)
}
override fun a1() {
val (numbers, boards) = readInput()
for (number in numbers)
for (board in boards) {
board.draw(number)
if (board.hasWon()) {
println(number * board.sum())
return
}
}
println("no board has won")
}
override fun a2() {
val (numbers, boards) = readInput()
for (number in numbers) {
val it = boards.iterator()
while (it.hasNext()) {
val board = it.next()
board.draw(number)
if (board.hasWon()) it.remove()
if (boards.size == 0) {
println(number * board.sum())
return
}
}
}
println("no board has won")
}
}