I did mine entirely with regular expressions.
# advent-of-code
t
I did mine entirely with regular expressions.
Copy code
class Day04(input: String) {

    private val passports: List<String> = input.split("\n\n")

    fun solvePart1(): Int =
        passports
            .count { passport -> expectedFields.all { passport.contains(it)} }

    fun solvePart2(): Int =
        passports
            .count { passport -> fieldPatterns.all { it.containsMatchIn(passport) } }

    companion object {
        private val expectedFields = listOf("byr:", "iyr:", "eyr:", "hgt:", "hcl:", "ecl:", "pid:")
        private val fieldPatterns = listOf(
            """\bbyr:(19[2-9][0-9]|200[0-2])\b""",
            """\biyr:(201[0-9]|2020)\b""",
            """\beyr:(202[0-9]|2030)\b""",
            """\bhgt:((1([5-8][0-9]|9[0-3])cm)|((59|6[0-9]|7[0-6])in))\b""",
            """\bhcl:#[0-9a-f]{6}\b""",
            """\becl:(amb|blu|brn|gry|grn|hzl|oth)\b""",
            """\bpid:[0-9]{9}\b"""
        ).map { it.toRegex() }
    }

}
😰 1
j
Haha I've used a few regexes but it never occurred to me to do the range checks like this, nice!
t
I wrote a ton of PERL early in my career, so I have a good foundation in regex. My problem with this is how to explain it to people. 🙂 And if this was a real program I'd probably coerce this into a class and validate it more directly.
b
Yep I think that's what the fastest people should have done
awk+sed it should be pretty quick
you could have done a regexp for expectedFields as well 😉
t
Yeah, I could have, and I might rewrite it to do that so I can make my explanation cleaner. But I'm thinking if I write about doing what I did with Part 1 and making the lesson of Part 2 "but what if the text is more complicated...". I dunno. I'm off work today so I'm giving it time to sit while I think about it before writing it up.
a
That's just a bit scary 🙂 How are you ignoring the optional country field 'cid'?
t
I'm just ignoring it. I don't have "cid" in my code at all.
What would have totally thrown this off is if the input had bogus fields. My method wouldn't have worked as well, but my input does not seem to have fields that shouldn't be there.
a
Got it now. Thought you were comparing each field against a regex but you are actually checking each regex to see if there is a matching field in the passport.
t
Yup! Granted if we were actually going to do something with this data I would have parsed it into a data class or something and written a proper validator. But since we're just looking to make sure that text matches a pattern and nothing else, I'm fine with regexes. Gives me a chance to talk about text matching, etc.