-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDay04.cs
107 lines (102 loc) · 4.13 KB
/
Day04.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
using System;
namespace AdventOfCode2024
{
internal class Day04 : Solution
{
readonly string[] grid;
public Day04(string input)
: base(input)
{
grid = input.Split(
'\n',
StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries
);
}
public override string Part1()
{
int matches = 0;
// iterate each cell
int rowmax = grid.Length;
for (int row = 0; row < rowmax; row++)
{
int colmax = grid[row].Length;
for (int col = 0; col < colmax; col++)
{
// all matches must begin with X
if (grid[row][col] == 'X')
{
// consider neighbours
for (int i = -1; i <= 1; i++)
{
for (int j = -1; j <= 1; j++)
{
// check if MAS appears in one direction
if (
Match(grid, 'M', row + i, col + j, rowmax, colmax) &&
Match(grid, 'A', row + (2 * i), col + (2 * j), rowmax, colmax) &&
Match(grid, 'S', row + (3 * i), col + (3 * j), rowmax, colmax)
)
{
matches++;
}
}
}
}
}
}
return matches.ToString();
}
public override string Part2()
{
int matches = 0;
int[] corners = { -1, 1 };
// iterate each cell
int rowmax = grid.Length;
for (int row = 0; row < rowmax; row++)
{
int colmax = grid[row].Length;
for (int col = 0; col < colmax; col++)
{
// all matches must begin with M
if (grid[row][col] == 'M')
{
// consider diagonal neighbours
foreach (int i in corners)
{
foreach (int j in corners)
{
if (
// check MAS appears diagonally in one direction
Match(grid, 'A', row + i, col + j, rowmax, colmax) &&
Match(grid, 'S', row + (2 * i), col + (2 * j), rowmax, colmax) &&
((
// either M is the far row and S is the far col
Match(grid, 'M', row + (2 * i), col, rowmax, colmax) &&
Match(grid, 'S', row, col + (2 * j), rowmax, colmax)
) || (
// or S is the far row and M is the far row
Match(grid, 'S', row + (2 * i), col, rowmax, colmax) &&
Match(grid, 'M', row, col + (2 * j), rowmax, colmax)
))
)
{
matches++;
}
}
}
}
}
}
// every X-MAS should be found twice, once for each M
return (matches / 2).ToString();
}
private bool Match(string[] grid, char chr, int row, int col, int rowmax, int colmax)
{
return (0 <= row) && // upper row valid
(row < rowmax) && // lower row valid
(0 <= col) && // left col valid
(col < colmax) && // right col valid
grid[row][col] == chr; // cell has desired value
}
}
}