diff --git a/day04/input2.sample b/day04/input2.sample new file mode 100644 index 0000000..b526855 --- /dev/null +++ b/day04/input2.sample @@ -0,0 +1,26 @@ +eyr:1972 cid:100 +hcl:#18171d ecl:amb hgt:170 pid:186cm iyr:2018 byr:1926 + +iyr:2019 +hcl:#602927 eyr:1967 hgt:170cm +ecl:grn pid:012533040 byr:1946 + +hcl:dab227 iyr:2012 +ecl:brn hgt:182cm pid:021572410 eyr:2020 byr:1992 cid:277 + +hgt:59cm ecl:zzz +eyr:2038 hcl:74454a iyr:2023 +pid:3556412378 byr:2007 + +pid:087499704 hgt:74in ecl:grn iyr:2012 eyr:2030 byr:1980 +hcl:#623a2f + +eyr:2029 ecl:blu cid:129 byr:1989 +iyr:2014 pid:896056539 hcl:#a97842 hgt:165cm + +hcl:#888785 +hgt:164cm byr:2001 iyr:2015 cid:88 +pid:545766238 ecl:hzl +eyr:2022 + +iyr:2010 hgt:158cm hcl:#b6652a ecl:blu byr:1944 eyr:2021 pid:093154719 \ No newline at end of file diff --git a/day04/solution01.rb b/day04/solution01.rb index ea7a646..19e6cd7 100755 --- a/day04/solution01.rb +++ b/day04/solution01.rb @@ -51,5 +51,4 @@ passports.each_value do |passport| end end -pp results - +pp results \ No newline at end of file diff --git a/day04/solution02.rb b/day04/solution02.rb new file mode 100755 index 0000000..66331da --- /dev/null +++ b/day04/solution02.rb @@ -0,0 +1,79 @@ +#!/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 \ No newline at end of file