-
Notifications
You must be signed in to change notification settings - Fork 10
/
Day04.cs
90 lines (76 loc) · 3.03 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
using System;
using System.Security.Cryptography;
using AdventOfCode.CSharp.Common;
namespace AdventOfCode.CSharp.Y2015.Solvers
{
public class Day04 : ISolver
{
public static void Solve(ReadOnlySpan<byte> input, Solution solution)
{
const byte zeroByte = (byte)'0';
const byte oneByte = (byte)'1';
using var provider = MD5.Create();
// create a buffer for the MD5 provider to store the result hash in
Span<byte> resultBuffer = stackalloc byte[provider.HashSize / 8];
ReadOnlySpan<byte> inputAsBytes = input.TrimEnd((byte)'\n');
int inputLen = inputAsBytes.Length;
int extraBytes = 1;
int n = 1;
int part1 = 0;
int part2 = 0;
// each iteration of this while loop increases the number of digits being tested
while (part2 == 0)
{
// buffer that stores the data being hashed
byte[] inputBuffer = new byte[inputLen + extraBytes];
// populate the first bytes of the input buffer with the problem input
inputAsBytes.CopyTo(inputBuffer);
// put the ASCII representation of '1' as the first byte and '0' for the remaining bytes
// this means that if we were testing 5 digits, then this would start at 10000
inputBuffer[inputLen] = oneByte;
for (int i = inputLen + 1; i < inputBuffer.Length; i++)
{
inputBuffer[i] = zeroByte;
}
// n will already be initialised at the correct value
int nEnd = n * 10;
for (; n < nEnd; n++)
{
_ = provider.TryComputeHash(inputBuffer, resultBuffer, out _);
if (resultBuffer[0] == 0 && resultBuffer[1] == 0)
{
if (part1 == 0)
{
if (resultBuffer[2] >> 4 == 0)
{
part1 = n;
}
}
else if (resultBuffer[2] == 0)
{
part2 = n;
break;
}
}
int curValue = n;
for (int i = inputBuffer.Length - 1; i >= inputBuffer.Length - extraBytes; i--)
{
if (curValue % 10 == 9)
{
inputBuffer[i] = zeroByte;
curValue /= 10;
}
else
{
inputBuffer[i]++;
break;
}
}
}
extraBytes++;
}
solution.SubmitPart1(part1);
solution.SubmitPart2(part2);
}
}
}