1
0
Fork 0

2020 day 4

This commit is contained in:
Lucidiot 2020-12-07 01:39:49 +01:00
parent 2543ec7db3
commit 2a3fe2951b
Signed by: lucidiot
GPG Key ID: 3358C1CA6906FB8D
2 changed files with 80 additions and 1 deletions

79
2020/4/day4.lua Normal file
View File

@ -0,0 +1,79 @@
#!/usr/bin/env lua
local passports, current = {}, {}
for line in io.lines() do
if line == "" then
table.insert(passports, current)
current = {}
end
for name, value in line:gmatch("(%a+):(%g+)") do
current[name] = value
end
end
table.insert(passports, current)
local function validate_byr(val)
val = tonumber(val)
return val and val >= 1920 and val <= 2002
end
local function validate_iyr(val)
val = tonumber(val)
return val and val >= 2010 and val <= 2020
end
local function validate_eyr(val)
val = tonumber(val)
return val and val >= 2020 and val <= 2030
end
local function validate_hgt(val)
local suffix = val:sub(-2)
val = tonumber(val:sub(1, -3))
if not val then return false end
if suffix == "cm" then
return val >= 150 and val <= 193
elseif suffix == "in" then
return val >= 59 and val <= 76
else return false end
end
local function validate_hcl(val)
return val and val:match("#%x%x%x%x%x")
end
local function validate_ecl(val)
return ({amb=true, blu=true, brn=true, gry=true, grn=true, hzl=true, oth=true})[val]
end
local function validate_pid(val)
return val and val:match("^%d%d%d%d%d%d%d%d%d$")
end
local required_fields = {
byr=validate_byr,
iyr=validate_iyr,
eyr=validate_eyr,
hgt=validate_hgt,
hcl=validate_hcl,
ecl=validate_ecl,
pid=validate_pid,
}
local function validate(run_checks)
local count = 0
for _, passport in ipairs(passports) do
local ok = 1
for field, validator in pairs(required_fields) do
if passport[field] == nil or (run_checks and not validator(passport[field])) then
ok = 0
break
end
end
count = count + ok
end
return count
end
print(validate(false))
print(validate(true))

View File

@ -9,7 +9,7 @@ My solutions to the Advent of Code puzzles.
1 ██ ██ ██ ██ ██
2 ██ ██ ██ ██ ██
3 ██ ██ ██ ██ ██
4 ██ ██ ██
4 ██ ██ ██ ██
5 ██ ██ ██
6 ██ ██
7 ██ ██