-
Notifications
You must be signed in to change notification settings - Fork 0
/
Day_3.cs
126 lines (102 loc) · 3.94 KB
/
Day_3.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
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
namespace AdventOfCode_2023
{
public class Day_3 : Day
{
public override long FirstPart()
{
int result = 0;
for (int i = 0; i < inputs.Length; i++)
{
string line = inputs[i];
for (int j = 0; j < line.Length; j++)
{
char c= line[j];
if (c != '.' && !Char.IsDigit(c))
{
List<string> surroundingNumbers = getSurroundingNumbers(i, j);
result += surroundingNumbers.Select(n => int.Parse(n)).Sum();
}
}
}
return result;
}
private List<string> getSurroundingNumbers(int lineNumber, int colNumber)
{
List<string> res = new List<string>();
string line = inputs[lineNumber];
if (lineNumber > 0)
{
if (colNumber > 0)
{
addPossibleNumberFromCoordinates(res, lineNumber - 1, colNumber - 1);//top left
}
addPossibleNumberFromCoordinates(res, lineNumber - 1, colNumber); //top
if (colNumber < line.Length - 1)
{
addPossibleNumberFromCoordinates(res, lineNumber - 1, colNumber + 1); //top right
}
}
if (colNumber > 0)
{
addPossibleNumberFromCoordinates(res, lineNumber, colNumber - 1);//left
}
if (colNumber < line.Length - 1)
{
addPossibleNumberFromCoordinates(res, lineNumber, colNumber + 1);//right
}
if (lineNumber < inputs.Length - 1)
{
if (colNumber > 0)
{
addPossibleNumberFromCoordinates(res, lineNumber + 1, colNumber - 1);// bottom left
}
addPossibleNumberFromCoordinates(res, lineNumber + 1, colNumber); //bottom
if (colNumber < line.Length - 1)
{
addPossibleNumberFromCoordinates(res, lineNumber + 1, colNumber + 1); //bottom right
}
}
return res;
}
private void addPossibleNumberFromCoordinates(List<string> numbers, int lineNumber, int colNumber)
{
string line = inputs[lineNumber];
if (Char.IsDigit(line[colNumber]))
{
int colNumberStart = colNumber;
int colNumberEnd = colNumber;
while (colNumberStart > 0 && Char.IsDigit(line[colNumberStart - 1]))
colNumberStart--;
while (colNumberEnd < line.Length - 1 && Char.IsDigit(line[colNumberEnd + 1]))
colNumberEnd++;
string number = line.Substring(colNumberStart, colNumberEnd - colNumberStart + 1);
if (!numbers.Contains(number))
{
numbers.Add(number);
}
}
}
public override long SecondPart()
{
int result = 0;
for (int i = 0; i < inputs.Length; i++)
{
string line = inputs[i];
for (int j = 0; j < line.Length; j++)
{
char c = line[j];
if (c == '*')
{
List<string> surroundingNumbers = getSurroundingNumbers(i, j);
if (surroundingNumbers.Count == 2)
{
int gearRatio = surroundingNumbers.Select(n => int.Parse(n)).Aggregate(1, (x,y) => x * y);
result += gearRatio;
}
}
}
}
return result;
}
}
}