From d6aa267e8e03dde70b59e262bb2aacdf3d071ec9 Mon Sep 17 00:00:00 2001 From: Danila Fedorin Date: Tue, 1 Dec 2020 21:13:43 -0800 Subject: [PATCH] Add day2 solution. --- day2.cr | 41 ++++++++++++++++++++++------------------- 1 file changed, 22 insertions(+), 19 deletions(-) diff --git a/day2.cr b/day2.cr index 83986bd..5020481 100644 --- a/day2.cr +++ b/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