Skip to content

Instantly share code, notes, and snippets.

@MikeRogers0
Last active December 4, 2020 10:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MikeRogers0/73bfbcde0bc245b3b09a51358f583044 to your computer and use it in GitHub Desktop.
Save MikeRogers0/73bfbcde0bc245b3b09a51358f583044 to your computer and use it in GitHub Desktop.
Advent Of Code - Day 4 (Part two) - Ruby
passports = File.open('input.txt').read.split("\n\n")
class Passport
REQUIRED_FIELDS = %w[
byr
iyr
eyr
hgt
hcl
ecl
pid
].freeze
def initialize(passport_string)
@passport_string = passport_string
convert_passport_string_to_hash!
end
def valid?
puts ""
puts ""
REQUIRED_FIELDS.all? do |field|
puts "#{field}: #{@parts[field]} = #{ send("#{field}_valid?") if @parts[field]}"
@parts[field] && send("#{field}_valid?")
end
end
private
def convert_passport_string_to_hash!
@parts = @passport_string
.split("\n")
.join(' ')
.split(' ')
.collect { |part| part.split(':') }
.to_h
end
# four digits; at least 1920 and at most 2002.
def byr_valid?
byr = @parts['byr'].to_i
@parts['byr'].length == 4 && byr >= 1920 && byr <= 2002
end
# four digits; at least 2010 and at most 2020.
def iyr_valid?
iyr = @parts['iyr'].to_i
@parts['iyr'].length == 4 && iyr >= 2010 && iyr <= 2020
end
# four digits; at least 2020 and at most 2030.
def eyr_valid?
eyr = @parts['eyr'].to_i
@parts['eyr'].length == 4 && eyr >= 2020 && eyr <= 2030
end
# If cm, the number must be at least 150 and at most 193.
# If in, the number must be at least 59 and at most 76.
def hgt_valid?
hgt_value = @parts['hgt'].sub(/in|cm/, '').to_i
if @parts['hgt'].include?('cm')
hgt_value >= 150 && hgt_value <= 193
else
hgt_value >= 59 && hgt_value <= 76
end
end
# a # followed by exactly six characters 0-9 or a-f.
def hcl_valid?
@parts['hcl'].match?(/^#[0-9a-f]{6}$/i)
end
# exactly one of: amb blu brn gry grn hzl oth.
def ecl_valid?
['amb', 'blu', 'brn', 'gry', 'grn', 'hzl', 'oth'].include?(@parts['ecl'])
end
# a nine-digit number, including leading zeroes.
def pid_valid?
@parts['pid'].length == 9
end
end
puts passports
.collect { |passport_string| Passport.new(passport_string) }
.select(&:valid?)
.count
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment