Day 2: Revisited reg ex parsing, but it really turned out to be too complicated for me. Simplified part 1 a little.

This commit is contained in:
Chris Hodges 2023-12-02 07:42:10 +01:00
parent db8acdd483
commit 15d5e2ade8

View File

@ -57,21 +57,15 @@ Game 5: 6 red, 1 blue, 3 green; 2 blue, 1 red, 2 green
fun part1(input: List<String>): Int { fun part1(input: List<String>): Int {
val limits = mapOf("red" to 12, "green" to 13, "blue" to 14) val limits = mapOf("red" to 12, "green" to 13, "blue" to 14)
return input.map { return input.map {
val lg = it.split(":") "Game (\\d+): (.*)".toRegex().matchEntire(it)?.destructured
val sets = lg[1].trim().split(";") ?.let { (id, game) ->
var possible = lg[0].split(" ")[1].toInt() var possible = id.toInt()
exit@ for (s in sets) { game.replace(";", "").replace(",", "")
val boxes = s.trim().split(",") .split(" ").chunked(2)
for (b in boxes) { .forEach { (num, col) -> if (num.toInt() > limits[col]!!) possible = 0 }
val (num, col) = b.trim().split(" ") possible
if (num.toInt() > limits[col]!!) {
possible = 0
break@exit
}
} }
} }.sumOf { it!! }
possible
}.sum()
} }
fun part2(input: List<String>): Int { fun part2(input: List<String>): Int {
@ -83,7 +77,7 @@ Game 5: 6 red, 1 blue, 3 green; 2 blue, 1 red, 2 green
val boxes = s.trim().split(",") val boxes = s.trim().split(",")
for (b in boxes) { for (b in boxes) {
val (num, col) = b.trim().split(" ") val (num, col) = b.trim().split(" ")
powerMap.merge(col, num.toInt()) { a, b -> max(a, b) } powerMap.merge(col, num.toInt(), ::max)
} }
} }
powerMap.values.reduce { a, b -> a * b } powerMap.values.reduce { a, b -> a * b }