-
Notifications
You must be signed in to change notification settings - Fork 10
/
Day06.cs
105 lines (88 loc) · 2.77 KB
/
Day06.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
using AdventOfCode.CSharp.Common;
using System;
namespace AdventOfCode.CSharp.Y2015.Solvers;
public class Day06 : ISolver
{
public static void Solve(ReadOnlySpan<byte> input, Solution solution)
{
const int part1Mask = 1 << 16;
int[,] grid = new int[1000, 1000];
foreach (Range instructionRange in input.SplitLines())
{
ReadOnlySpan<byte> instruction = input[instructionRange];
int x, y;
int x1, y1, x2, y2;
switch (instruction[6])
{
case (byte)' ':
// toggle
ParseArea(instruction[7..], out x1, out y1, out x2, out y2);
for (x = x1; x <= x2; x++)
{
for (y = y1; y <= y2; y++)
{
grid[x, y] = (grid[x, y] ^ part1Mask) + 2;
}
}
break;
case (byte)'f':
// turn off
ParseArea(instruction[9..], out x1, out y1, out x2, out y2);
for (x = x1; x <= x2; x++)
{
for (y = y1; y <= y2; y++)
{
grid[x, y] = Math.Max((grid[x, y] & 0xFFFF) - 1, 0);
}
}
break;
case (byte)'n':
// turn on
ParseArea(instruction[8..], out x1, out y1, out x2, out y2);
for (x = x1; x <= x2; x++)
{
for (y = y1; y <= y2; y++)
{
grid[x, y] = (grid[x, y] | part1Mask) + 1;
}
}
break;
}
}
int part1 = 0;
int part2 = 0;
foreach (int gridValue in grid)
{
part1 += gridValue >> 16;
part2 += gridValue & 0xFFFF;
}
solution.SubmitPart1(part1);
solution.SubmitPart2(part2);
}
private static void ParseArea(ReadOnlySpan<byte> regionStr, out int x1, out int y1, out int x2, out int y2)
{
byte c;
int i = 0;
x1 = 0;
while ((c = regionStr[i++]) != ',')
{
x1 = x1 * 10 + (c - '0');
}
y1 = 0;
while ((c = regionStr[i++]) != ' ')
{
y1 = y1 * 10 + (c - '0');
}
i += 8; // length of "through "
x2 = 0;
while ((c = regionStr[i++]) != ',')
{
x2 = x2 * 10 + (c - '0');
}
y2 = 0;
while (i < regionStr.Length)
{
y2 = y2 * 10 + (regionStr[i++] - '0');
}
}
}