43 lines
1.4 KiB
Kotlin
43 lines
1.4 KiB
Kotlin
package be.vandewalleh.aoc.days
|
|
|
|
import be.vandewalleh.aoc.utils.input.Day
|
|
import be.vandewalleh.aoc.utils.input.Text
|
|
|
|
private typealias Entry = Pair<String, String>
|
|
private typealias Entries = List<Entry>
|
|
|
|
@Day(4)
|
|
class Day04(@Text val input: String) {
|
|
|
|
val entries = input.split("\n\n").map {
|
|
it.split(" ", "\n").map { it.split(":").let { (k, v) -> k to v } }
|
|
}
|
|
|
|
private fun Entries.hasRequiredKeys() = map { it.first }
|
|
.containsAll(listOf("byr", "iyr", "eyr", "hgt", "hcl", "ecl", "pid"))
|
|
|
|
fun part1() = entries.count { it.hasRequiredKeys() }
|
|
|
|
private val hclRegex = Regex("#[0-9a-f]{6}")
|
|
private val pidRegex = Regex("[0-9]{9}")
|
|
|
|
private fun Entry.isValid() = let { (k, v) ->
|
|
when (k) {
|
|
"byr" -> v.toInt() in 1920..2002
|
|
"iyr" -> v.toInt() in 2010..2020
|
|
"eyr" -> v.toInt() in 2020..2030
|
|
"hgt" -> when {
|
|
v.endsWith("cm") -> v.removeSuffix("cm").toInt() in 150..193
|
|
v.endsWith("in") -> v.removeSuffix("in").toInt() in 59..76
|
|
else -> false
|
|
}
|
|
"hcl" -> v.matches(hclRegex)
|
|
"ecl" -> v in arrayOf("amb", "blu", "brn", "gry", "grn", "hzl", "oth")
|
|
"pid" -> v.matches(pidRegex)
|
|
else -> true
|
|
}
|
|
}
|
|
|
|
fun part2() = entries.count { it.hasRequiredKeys() && it.all { it.isValid() } }
|
|
}
|