Add day2 solution.

This commit is contained in:
Danila Fedorin 2020-12-01 21:13:43 -08:00
parent 125317f146
commit d6aa267e8e

41
day2.cr
View File

@ -1,17 +1,23 @@
INPUT = File.read("day2.txt").lines.map(&.chomp) 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 def part1
input = INPUT.clone input = INPUT.clone
total = 0 total = input.count do |line|
input.each do |line| next false unless data = parse(line)
data = line.match(/([0-9]+)-([0-9]+) ([a-z]): ([a-z]+)/) min, max, char, str = data
next unless data
min = data[1].to_i
max = data[2].to_i
char = data[3][0]
str = data[4]
count = str.chars.count(char) count = str.chars.count(char)
total += 1 if count >= min && count <= max count >= min && count <= max
end end
puts total puts total
@ -19,17 +25,14 @@ end
def part2 def part2
input = INPUT.clone input = INPUT.clone
total = 0 total = input.count do |line|
input.each do |line| next false unless data = parse(line)
data = line.match(/([0-9]+)-([0-9]+) ([a-z]): ([a-z]+)/) min, max, char, str = data
next unless data min -= 1
min = data[1].to_i - 1 max -= 1
max = data[2].to_i - 1 ((str[min] == char) || (str[max] == char) ) && str[min] != str[max]
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]
end end
puts total puts total
end end