Add day2 solution.
This commit is contained in:
parent
125317f146
commit
d6aa267e8e
41
day2.cr
41
day2.cr
|
@ -1,17 +1,23 @@
|
|||
INPUT = File.read("day2.txt").lines.map(&.chomp)
|
||||
|
||||
def parse(line)
|
||||
data = line.match(/([0-9]+)-([0-9]+) ([a-z]): ([a-z]+)/)
|
||||
data.try do |data|
|
||||
min = data[1].to_i
|
||||
max = data[2].to_i
|
||||
char = data[3][0]
|
||||
str = data[4]
|
||||
{min,max,char,str}
|
||||
end
|
||||
end
|
||||
|
||||
def part1
|
||||
input = INPUT.clone
|
||||
total = 0
|
||||
input.each do |line|
|
||||
data = line.match(/([0-9]+)-([0-9]+) ([a-z]): ([a-z]+)/)
|
||||
next unless data
|
||||
min = data[1].to_i
|
||||
max = data[2].to_i
|
||||
char = data[3][0]
|
||||
str = data[4]
|
||||
total = input.count do |line|
|
||||
next false unless data = parse(line)
|
||||
min, max, char, str = data
|
||||
count = str.chars.count(char)
|
||||
total += 1 if count >= min && count <= max
|
||||
count >= min && count <= max
|
||||
end
|
||||
|
||||
puts total
|
||||
|
@ -19,17 +25,14 @@ end
|
|||
|
||||
def part2
|
||||
input = INPUT.clone
|
||||
total = 0
|
||||
input.each do |line|
|
||||
data = line.match(/([0-9]+)-([0-9]+) ([a-z]): ([a-z]+)/)
|
||||
next unless data
|
||||
min = data[1].to_i - 1
|
||||
max = data[2].to_i - 1
|
||||
char = data[3][0]
|
||||
str = data[4]
|
||||
count = str.chars.count(char)
|
||||
total += 1 if ((str[min] == char) || (str[max] == char) ) && str[min] != str[max]
|
||||
total = input.count do |line|
|
||||
next false unless data = parse(line)
|
||||
min, max, char, str = data
|
||||
min -= 1
|
||||
max -= 1
|
||||
((str[min] == char) || (str[max] == char) ) && str[min] != str[max]
|
||||
end
|
||||
|
||||
puts total
|
||||
end
|
||||
|
||||
|
|
Loading…
Reference in New Issue
Block a user