DEV Community

loading...

Discussion on: Advent of Code 2020 Solution Megathread - Day 4: Passport Processing

Collapse
totally_chase profile image
Phantz • Edited

would anyone be interested in a solution written entirely in C, without regex or hashtables

static char const* formats[] = {
    " byr:19%*2[0-9]%n", " byr:200%*1[0-2]%n",
    " iyr:201%*1[0-9]%n", " iyr:2020%n",
    " eyr:202%*1[0-9]%n", " eyr:2030%n",
    " hgt:1%*1[5-8]%*1[0-9]cm%n", " hgt:19%*1[0-3]cm%n",
        " hgt:59in%n", " hgt:6%*1[0-9]in%n", " hgt:7%*1[0-6]in%n",
    " hcl:#%*x%n",
    " ecl:amb%n", " ecl:blu%n", " ecl:brn%n", " ecl:gr%*1[yn]%n", " ecl:hzl%n", " ecl:oth%n",
    " pid:%*9[0-9]%n",
    " cid:%*s%n"
};

static bool is_valid(char const* s)
{
    size_t count = 0;
    for (int n = 0, prevn = -1; n != prevn && s[n] != '\0';)
    {
        prevn = n;
        for (size_t i = 0; i < sizeof formats / sizeof * formats; i++)
        {
            int _n = 0;
            sscanf(s + n, formats[i], &_n);
            if (_n != 0)
            {
                n += _n;
                count += 1;
                formats[i] = "";
                break;
            }
        }
    }
    return count >= 7;
}
Enter fullscreen mode Exit fullscreen mode

The input s to is_valid should be a full passport string (what you get after splitting by double new lines). It does parsing + validation at once and eagerly exits if any field validation fails.

Yes, I know - very cursed. 'twas just for fun, and to prove a point ;)