-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDay04.cs
More file actions
113 lines (95 loc) · 3.29 KB
/
Day04.cs
File metadata and controls
113 lines (95 loc) · 3.29 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
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
using _2024.Utils;
namespace _2024._04;
public class Day04 : Base
{
public Day04(bool example) : base(example)
{
Day = "4";
}
public override object PartOne()
{
string[] input = ReadInput();
string puzzle = String.Join("", input);
int numCols = input[0].Length, numRows = input.Length;
int xmasCount = 0;
ValueTuple<int, int>[] directions =
[
(1, 1), // Diagonal down-right
(1, -1), // Diagonal down-left
(-1, 1), // Diagonal up-right
(-1, -1), // Diagonal up-left
(-1, 0), // up
(1, 0), // down
(0, 1), // right
(0, -1) // left
];
Dictionary<string, string> test = new Dictionary<string, string>();
foreach (var (letter, idx) in puzzle.Enumerate())
{
test.Clear();
int column = idx % input.Length;
int row = idx / input.Length;
if (letter != 'X')
{
continue;
}
for (int mod = 1; mod <= 3; mod++)
{
foreach (var (dirRow, dirCol) in directions)
{
int newRow = row + mod * dirRow;
int newCol = column + mod * dirCol;
string key = $"{dirRow}{dirCol}";
test.TryAdd(key, "X");
if (newRow >= 0 && newRow < numRows && newCol >= 0 && newCol < numCols)
{
test[key] += puzzle[newRow * numCols + newCol];
}
}
}
xmasCount += test.Values.Count(x => x == "XMAS" || x == "SAMX");
}
return xmasCount;
}
public override object PartTwo()
{
string[] input = ReadInput();
string puzzle = String.Join("", input);
int numCols = input[0].Length, numRows = input.Length;
int xmasCount = 0;
ValueTuple<int, int>[] directions =
[
(1, 1), // Diagonal down-right
(1, -1), // Diagonal down-left
(-1, 1), // Diagonal up-right
(-1, -1), // Diagonal up-left
];
foreach (var (letter, idx) in puzzle.Enumerate())
{
int column = idx % input.Length;
int row = idx / input.Length;
if (letter != 'A')
{
continue;
}
// only one step in each direction
// if one is oob it cant be x-mas
if (row + 1 >= numRows || column + 1 >= numCols || column - 1 < 0 || row - 1 < 0)
{
continue;
}
string test = "";
foreach (var (dirRow, dirCol) in directions)
{
int newRow = row + dirRow;
int newCol = column + dirCol;
test += puzzle[newRow * numCols + newCol];
}
if (test is "MMSS" or "SSMM" or "MSMS" or "SMSM")
{
xmasCount++;
}
}
return xmasCount;
}
}