1
0
Files
Advent-of-Code/days/src/main/kotlin/Day04.kt
T
2020-12-07 22:31:48 +01:00

50 lines
1.5 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 = input.value.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() } }
}
fun main() = with(createDay<Day04>()) {
println(part1())
println(part2())
}