Created
December 3, 2020 03:17
-
-
Save thiagoramos23/79343a828732d08ac332a88afac5ecb9 to your computer and use it in GitHub Desktop.
Advent of Code Day 2
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# PART 01 | |
class Password | |
attr_accessor :min, :max, :letter, :value | |
def initialize(min:, max:, letter:, value:) | |
@min = min.to_i | |
@max = max.to_i | |
@letter = letter | |
@value = value | |
end | |
def valid_password? | |
letters = value.scan /\w/ | |
count_letters = letters.select { |l| l == letter }.count | |
min <= count_letters && count_letters <= max | |
end | |
def to_s | |
"#{letter} #{min} #{max} #{value}" | |
end | |
end | |
contents = File.open("input.txt").read.split("\n") | |
passwords = [] | |
contents.map do |item| | |
key, value = item.split(':') | |
quantity, letter = key.split(' ') | |
passwords << Password.new(min: quantity.split('-').first, max: quantity.split('-').last, letter: letter, value: value) | |
end | |
puts "Total: #{passwords.select { |pass| pass.valid_password? }.count}" | |
# PART 02 | |
class Password | |
attr_accessor :min, :max, :letter, :value | |
def initialize(min:, max:, letter:, value:) | |
@min = min.to_i - 1 | |
@max = max.to_i - 1 | |
@letter = letter | |
@value = value | |
end | |
def valid_password? | |
letters = value.scan /\w/ | |
return true if letters[min] == letter && letters[max] != letter | |
return true if letters[min] != letter && letters[max] == letter | |
false | |
end | |
def to_s | |
"#{letter} #{min} #{max} #{value}" | |
end | |
end | |
contents = File.open("input.txt").read.split("\n") | |
passwords = [] | |
contents.map do |item| | |
key, value = item.split(':') | |
quantity, letter = key.split(' ') | |
passwords << Password.new(min: quantity.split('-').first, max: quantity.split('-').last, letter: letter, value: value) | |
end | |
puts "Total: #{passwords.select { |pass| pass.valid_password? }.count}" | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment