Optimisations
This commit is contained in:
parent
0454187323
commit
4008858df8
@ -12,17 +12,16 @@ typealias Entries = List<Entry>
|
|||||||
class Day04(@Text val input: Input<String>) {
|
class Day04(@Text val input: Input<String>) {
|
||||||
|
|
||||||
val entries: List<Entries> = input.value.trim().split("\n\n").map {
|
val entries: List<Entries> = input.value.trim().split("\n\n").map {
|
||||||
it.replace("\n", " ")
|
it.replace("\n", " ").split(" ").map { it.split(":").let { (k, v) -> k.trim() to v.trim() } }
|
||||||
.splitToSequence(" ")
|
|
||||||
.map { it.split(":") }
|
|
||||||
.map { (k, v) -> k.trim() to v.trim() }
|
|
||||||
.toList()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun Entries.hasRequiredKeys() = map { it.first }
|
private fun Entries.hasRequiredKeys() = map { it.first }
|
||||||
.containsAll(listOf("byr", "iyr", "eyr", "hgt", "hcl", "ecl", "pid"))
|
.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) ->
|
private fun Entry.hasValidValues() = let { (k, v) ->
|
||||||
when (k) {
|
when (k) {
|
||||||
@ -34,18 +33,14 @@ class Day04(@Text val input: Input<String>) {
|
|||||||
v.endsWith("in") -> v.removeSuffix("in").toInt() in 59..76
|
v.endsWith("in") -> v.removeSuffix("in").toInt() in 59..76
|
||||||
else -> false
|
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")
|
"ecl" -> v in arrayOf("amb", "blu", "brn", "gry", "grn", "hzl", "oth")
|
||||||
"pid" -> v.matches("^[0-9]{9}$".toRegex())
|
"pid" -> v.matches(pidRegex)
|
||||||
else -> true
|
else -> true
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fun part2() = entries
|
fun part2() = entries.count { it.hasRequiredKeys() && it.all { it.hasValidValues() } }
|
||||||
.asSequence()
|
|
||||||
.filter { it.hasRequiredKeys() }
|
|
||||||
.filter { it.all { it.hasValidValues() } }
|
|
||||||
.count()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fun main() = with(createDay<Day04>()) {
|
fun main() = with(createDay<Day04>()) {
|
||||||
|
|||||||
Loading…
x
Reference in New Issue
Block a user