-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathDay05.cs
108 lines (93 loc) · 2.76 KB
/
Day05.cs
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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
namespace AdventOfCode._2021
{
public class Day05
{
private readonly IEnumerable<(IntVec2 p0, IntVec2 p1)> _input;
private Dictionary<IntVec2, int> _map = new();
public Day05()
{
_input = File.ReadAllLines("Inputs/Day05.txt")
.Select(l => l.Split(new[] { ",", " ", "->" }, StringSplitOptions.RemoveEmptyEntries))
.Select(tok => (new IntVec2(tok[0], tok[1]), new IntVec2(tok[2], tok[3])));
}
[Fact]
public void Part1()
{
foreach (var line in _input)
AddNonDiagonalLine(line.p0, line.p1);
int answer = _map.Values.Count(v => v > 1);
Assert.Equal(5576, answer);
}
[Fact]
public void Part2()
{
foreach (var line in _input)
AddLine(line.p0, line.p1);
int answer = _map.Values.Count(v => v > 1);
Assert.Equal(18144, answer);
}
private void AddLine(IntVec2 p0, IntVec2 p1)
{
if (p0.X != p1.X && p0.Y != p1.Y)
{
int x0 = p0.X;
int x1 = p1.X;
int y0 = p0.Y;
int y1 = p1.Y;
if (x1 < x0)
{
x0 = p1.X;
x1 = p0.X;
y0 = p1.Y;
y1 = p0.Y;
}
int j = y0;
bool dec = y1 < y0;
for (int i = x0; i <= x1; i++)
{
AddPoint(new IntVec2(i, j));
if (dec)
j--;
else
j++;
}
}
else
AddNonDiagonalLine(p0, p1);
}
private void AddNonDiagonalLine(IntVec2 p0, IntVec2 p1)
{
if (p0.X != p1.X && p0.Y == p1.Y)
{
int x0 = p0.X;
int x1 = p1.X;
if (x1 < x0)
{
x0 = p1.X;
x1 = p0.X;
}
for (int i = x0; i <= x1; i++)
AddPoint(new IntVec2(i, p0.Y));
}
if (p0.Y != p1.Y && p0.X == p1.X)
{
int y0 = p0.Y;
int y1 = p1.Y;
if (y1 < y0)
{
y0 = p1.Y;
y1 = p0.Y;
}
for (int j = y0; j <= y1; j++)
AddPoint(new IntVec2(p0.X, j));
}
}
private void AddPoint(IntVec2 p)
{
if (!_map.ContainsKey(p))
_map[p] = 1;
else
_map[p]++;
}
}
}