AdventOfCode-2020/day4.cr

81 lines
1.8 KiB
Crystal
Raw Normal View History

2020-12-03 21:22:52 -08:00
INPUT = File.read("day4.txt").lines.map(&.chomp)
2020-12-03 21:41:49 -08:00
def parse_passport(string)
new_hash = {} of String => String
string.split(" ").each do |field|
k,v = field.split(":")
new_hash[k] = v
end
new_hash
end
def parse_passports(lines)
passports = [] of Hash(String, String)
passport = [] of String
lines.each do |line|
unless line.empty?
passport << line
2020-12-03 21:22:52 -08:00
next
end
2020-12-03 21:41:49 -08:00
passports << parse_passport(passport.join(" "))
passport = [] of String
2020-12-03 21:22:52 -08:00
end
2020-12-03 21:41:49 -08:00
passports << parse_passport(passport.join(" "))
end
2020-12-03 21:22:52 -08:00
2020-12-03 21:41:49 -08:00
def part1
input = INPUT.clone
passports = parse_passports(input)
total = passports.count do |passport|
["byr", "iyr", "eyr", "hgt", "hcl", "ecl", "pid"].all? do |key|
passport.has_key? key
2020-12-03 21:22:52 -08:00
end
2020-12-03 21:41:49 -08:00
end
puts total
end
2020-12-03 21:22:52 -08:00
2020-12-03 21:41:49 -08:00
def part2
input = INPUT.clone
passports = parse_passports(input)
total = passports.count do |passport|
next unless value = passport["byr"]?
2020-12-03 21:22:52 -08:00
value = value.to_i32
next unless value >= 1920 && value <= 2002
2020-12-03 21:41:49 -08:00
next unless value = passport["iyr"]?
2020-12-03 21:22:52 -08:00
value = value.to_i32
next unless value >= 2010 && value <= 2020
2020-12-03 21:41:49 -08:00
next unless value = passport["eyr"]?
2020-12-03 21:22:52 -08:00
value = value.to_i32
next unless value >= 2020 && value <= 2030
2020-12-03 21:41:49 -08:00
next unless value = passport["hgt"]?
2020-12-03 21:22:52 -08:00
next unless value.ends_with?("cm") || value.ends_with?("in")
ivalue = value[0..-3].to_i32
if value.ends_with? "cm"
next unless ivalue >= 150 && ivalue <= 193
else
next unless ivalue >= 59 && ivalue <= 76
end
2020-12-03 21:41:49 -08:00
next unless value = passport["hcl"]?
2020-12-03 21:22:52 -08:00
next unless value[0] == '#' && (value[1..]).to_i32(16)
2020-12-03 21:41:49 -08:00
next unless value = passport["ecl"]?
2020-12-03 21:22:52 -08:00
next unless "amb blu brn gry grn hzl oth".split(" ").includes? value
2020-12-03 21:41:49 -08:00
next unless value = passport["pid"]?
2020-12-03 21:22:52 -08:00
next unless value.size == 9
next unless value = value.to_i32?
2020-12-03 21:41:49 -08:00
true
2020-12-03 21:22:52 -08:00
end
puts total
end
part1
part2