-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathDay04.cs
More file actions
82 lines (67 loc) · 2.31 KB
/
Day04.cs
File metadata and controls
82 lines (67 loc) · 2.31 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
using System.Text.RegularExpressions;
namespace AdventOfCode._2020;
public class Day04
{
private string _input;
public Day04()
{
_input = File.ReadAllText("Inputs/Day04.txt");
}
[Fact]
public void Part1()
{
MatchCollection matches = s_Regex.Matches(_input);
int answer = matches.Count(m =>
{
Group group = m.Groups["key"];
if (group.Captures.Count == 7 && m.Value.Contains("cid"))
return false;
return true;
});
Assert.Equal(230, answer);
}
[Fact]
public void Part2()
{
MatchCollection matches = s_Regex2.Matches(_input);
int answer = matches.Count(m =>
{
CaptureCollection captures = m.Groups["x"].Captures;
foreach (Capture capture in captures)
{
string[] tokens = capture.Value.Split(':');
string key = tokens[0];
string value = tokens[1];
if (key == "cid" && captures.Count == 7)
return false;
int num = 0;
if (int.TryParse(value, out num))
{
if ((key == "byr" && num is < 1920 or > 2002) ||
(key == "iyr" && num is < 2010 or > 2020) ||
(key == "eyr" && num is < 2020 or > 2030))
return false;
}
else if (key == "hgt")
{
num = int.Parse(value.Substring(0, value.Length - 2));
if (value.EndsWith("cm"))
{
if (num is < 150 or > 193)
return false;
}
else if (num is < 59 or > 76)
return false;
}
}
return true;
});
Assert.Equal(156, answer);
}
private static Regex s_Regex = new Regex(
@"(?'value'(?'key'byr|iyr|eyr|hgt|hcl|ecl|pid|cid):[#\w]+( |\r?\n)?){7,8}",
RegexOptions.Compiled);
private static Regex s_Regex2 = new Regex(
@"((?'x'(byr|iyr|eyr):\d{4}|hgt:\d{2,3}(cm|in)|hcl:#[a-f0-9]{6}|ecl:(amb|blu|brn|gry|grn|hzl|oth)|pid:\d{9}|cid:\w+)( |\r?\n)?){7,8}",
RegexOptions.Compiled);
}