AoC2020/day04/solution02.rb

79 lines
1.9 KiB
Ruby
Raw Normal View History

2020-12-04 15:10:32 +00:00
#!/bin/env ruby
def valid_passport? (passport, fields)
fields.each do |field|
return false if !(passport.has_key?(field.to_sym))
end
valid_colors = ['amb', 'blu', 'brn', 'gry', 'grn', 'hzl', 'oth']
passport.each_key do |key|
case key
when :byr
return false if (passport[key].to_i < 1920 or passport[key].to_i > 2002)
when :iyr
return false if (passport[key].to_i < 2010 or passport[key].to_i > 2020)
when :eyr
return false if (passport[key].to_i < 2020 or passport[key].to_i > 2030)
when :hgt
if passport[key][-2..] == 'in'
return false if (passport[key][..-3].to_i < 59 or passport[key][..-3].to_i > 76)
elsif passport[key][-2..] == 'cm'
return false if (passport[key][..-3].to_i < 150 or passport[key][..-3].to_i > 193)
else
return false
end
when :hcl
return false if !passport[key].match(/^[#][0-9a-f]{6}$/)
when :ecl
return false if !valid_colors.find { |color| color.match(passport[key]) }
when :pid
return false if !passport[key].match(/^[0-9]{9}$/)
end
end
true
end
text = File.read('./input')
passports = Hash.new
key = 0
passport = Hash.new
required_fields = [
"byr",
"iyr",
"eyr",
"hgt",
"hcl",
"ecl",
"pid",
# "cid"
]
results = {
:valid => 0,
:invalid => 0
}
text.each_line do |line|
line.strip!
if line == ''
passports[key] = passport
passport = Hash.new
key += 1
next
end
line.split(' ').each do |pair|
pair = pair.split(":")
passport[pair[0].to_sym] = pair[1]
end
end
passports[key] = passport
passports.each_value do |passport|
if valid_passport?(passport, required_fields)
results[:valid] += 1
else
results[:invalid] += 1
end
end
pp results