54 lines
1.6 KiB
Kotlin
54 lines
1.6 KiB
Kotlin
package be.vandewalleh.aoc.days
|
|
|
|
import be.vandewalleh.aoc.utils.input.Day
|
|
import be.vandewalleh.aoc.utils.input.Input
|
|
import be.vandewalleh.aoc.utils.input.Text
|
|
import be.vandewalleh.aoc.utils.input.createDay
|
|
|
|
typealias Entry = Pair<String, String>
|
|
typealias Entries = List<Entry>
|
|
|
|
@Day(4)
|
|
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()
|
|
}
|
|
|
|
private fun Entries.hasRequiredKeys() = map { it.first }
|
|
.containsAll(listOf("byr", "iyr", "eyr", "hgt", "hcl", "ecl", "pid"))
|
|
|
|
fun part1(): Int = entries.count { it.hasRequiredKeys() }
|
|
|
|
private fun Entry.hasValidValues(): Boolean {
|
|
val (k, v) = this
|
|
return when (k) {
|
|
"byr" -> v.toInt() in 1920..2002
|
|
"iyr" -> v.toInt() in 2010..2020
|
|
"eyr" -> v.toInt() in 2020..2030
|
|
"hgt" ->
|
|
if (v.endsWith("cm")) v.removeSuffix("cm").toInt() in 150..193
|
|
else v.removeSuffix("in").toInt() in 59..76
|
|
"hcl" -> v.matches("^#[0-9a-f]{6}$".toRegex())
|
|
"ecl" -> v in arrayOf("amb", "blu", "brn", "gry", "grn", "hzl", "oth")
|
|
"pid" -> v.matches("^[0-9]{9}$".toRegex())
|
|
else -> true
|
|
}
|
|
}
|
|
|
|
fun part2() = entries
|
|
.asSequence()
|
|
.filter { it.hasRequiredKeys() }
|
|
.filter { it.all { it.hasValidValues() } }
|
|
.count() - 1 // ???
|
|
}
|
|
|
|
fun main() = with(createDay<Day04>()) {
|
|
println(part1())
|
|
println(part2())
|
|
}
|