generated from kotlin-hands-on/advent-of-code-kotlin-template
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDay04.kt
77 lines (61 loc) · 2.22 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
fun main() {
fun parse(input: List<String>): Pair<List<Int>, Set<BingoBoard>> {
val bingoNumbers = input[0].split(",").map { it.toInt() }
val boards =
input.asSequence()
.drop(1)
.filter { it.isNotBlank() }
.map { it ->
it.split(" ")
.filter { it.isNotBlank() }
.map { it.toInt() }
}
.chunked(5)
.map { BingoBoard(it) }
.toSet()
return Pair(bingoNumbers, boards)
}
fun findWinners(
boards: Set<BingoBoard>,
bingoNumbers: List<Int>
): List<Pair<Int, BingoBoard>> {
val mutableBoards = boards.toMutableList()
val winners = buildList {
for (number in bingoNumbers) {
mutableBoards.replaceAll { it.markNumber(number) }
val winningBoards = mutableBoards.filter { it.isComplete() }
mutableBoards -= winningBoards.toSet()
winningBoards.forEach { add(Pair(it.score(number), it)) }
}
}
return winners
}
fun part1(input: List<String>): Int {
val (bingoNumbers, boards) = parse(input)
val winners = findWinners(boards, bingoNumbers)
return winners.first().first
}
fun part2(input: List<String>): Int {
val (bingoNumbers, boards) = parse(input)
val winners = findWinners(boards, bingoNumbers)
return winners.last().first
}
val testInput = readInput("Day04_test")
check(part1(testInput) == 4512)
check(part2(testInput) == 1924)
val input = readInput("Day04")
println(part1(input))
println(part2(input))
}
data class BingoBoard(val rows: List<List<Int>>) {
fun isComplete(): Boolean {
return this.rows.any { row -> row.all { it == -1 } }
|| this.rows.indices.any { col -> this.rows.all { it[col] == -1 } }
}
fun score(winningNumber: Int): Int {
return winningNumber * rows.sumOf { row -> row.filter { it != -1 }.sum() }
}
fun markNumber(number: Int): BingoBoard {
return BingoBoard(rows.map { row -> row.map { if (it == number) -1 else it } })
}
}