Day04 2021
This commit is contained in:
@@ -0,0 +1,52 @@
|
||||
package be.vandewalleh.aoc.days
|
||||
|
||||
import be.vandewalleh.aoc.utils.BaseDay
|
||||
import be.vandewalleh.aoc.utils.input.Day
|
||||
|
||||
@Day
|
||||
class Day04 : BaseDay() {
|
||||
private val parts by lazy { input.text.split("\n\n") }
|
||||
private val numbers by lazy { parts[0].split(',').map { it.toInt() } }
|
||||
private val boards by lazy {
|
||||
parts.drop(1)
|
||||
.map { it.lines().map { it.trim().split("\\s+".toRegex()).map { it.toInt() } } }
|
||||
}
|
||||
|
||||
override fun part1() = boards
|
||||
.map { playBoard(it, numbers) }
|
||||
.minByOrNull { it.first }!!
|
||||
.second
|
||||
|
||||
override fun part2() = boards
|
||||
.map { playBoard(it, numbers) }
|
||||
.maxByOrNull { it.first }!!
|
||||
.second
|
||||
|
||||
private fun playBoard(board: List<List<Int>>, numbers: List<Int>): Pair<Int, Int> {
|
||||
for (round in numbers.indices) {
|
||||
val usedNumbers = numbers.take(round)
|
||||
var winning = false
|
||||
for (line in board) {
|
||||
if (usedNumbers.containsAll(line)) {
|
||||
winning = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if (!winning) {
|
||||
for (i in board[0].indices) {
|
||||
val column = board.map { it[i] }
|
||||
if (usedNumbers.containsAll(column)) {
|
||||
winning = true
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
if (winning) {
|
||||
val unmarkedNumbers = board.flatten().toMutableSet().also { it.removeAll(usedNumbers) }
|
||||
return round to unmarkedNumbers.sum() * usedNumbers.last()
|
||||
}
|
||||
}
|
||||
error("No wins")
|
||||
}
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user