1
0

Optimisations

This commit is contained in:
Hubert Van De Walle 2020-12-05 00:01:23 +01:00
parent 0454187323
commit 4008858df8

View File

@ -12,17 +12,16 @@ typealias Entries = List<Entry>
class Day04(@Text val input: Input<String>) {
val entries: List<Entries> = input.value.trim().split("\n\n").map {
it.replace("\n", " ")
.splitToSequence(" ")
.map { it.split(":") }
.map { (k, v) -> k.trim() to v.trim() }
.toList()
it.replace("\n", " ").split(" ").map { it.split(":").let { (k, v) -> k.trim() to v.trim() } }
}
private fun Entries.hasRequiredKeys() = map { it.first }
.containsAll(listOf("byr", "iyr", "eyr", "hgt", "hcl", "ecl", "pid"))
fun part1(): Int = entries.count { it.hasRequiredKeys() }
fun part1() = entries.count { it.hasRequiredKeys() }
private val hclRegex = "^#[0-9a-f]{6}$".toRegex()
private val pidRegex = "^[0-9]{9}$".toRegex()
private fun Entry.hasValidValues() = let { (k, v) ->
when (k) {
@ -34,18 +33,14 @@ class Day04(@Text val input: Input<String>) {
v.endsWith("in") -> v.removeSuffix("in").toInt() in 59..76
else -> false
}
"hcl" -> v.matches("^#[0-9a-f]{6}$".toRegex())
"hcl" -> v.matches(hclRegex)
"ecl" -> v in arrayOf("amb", "blu", "brn", "gry", "grn", "hzl", "oth")
"pid" -> v.matches("^[0-9]{9}$".toRegex())
"pid" -> v.matches(pidRegex)
else -> true
}
}
fun part2() = entries
.asSequence()
.filter { it.hasRequiredKeys() }
.filter { it.all { it.hasValidValues() } }
.count()
fun part2() = entries.count { it.hasRequiredKeys() && it.all { it.hasValidValues() } }
}
fun main() = with(createDay<Day04>()) {