-
Notifications
You must be signed in to change notification settings - Fork 10
/
Day02.cs
62 lines (52 loc) · 1.57 KB
/
Day02.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
using AdventOfCode.CSharp.Common;
using AdventOfCode.CSharp.Y2019.Common;
using System;
namespace AdventOfCode.CSharp.Y2019.Solvers;
public class Day02 : ISolver
{
public static void Solve(ReadOnlySpan<byte> input, Solution solution)
{
ReadOnlySpan<int> intCode = IntCode.ParseFromInput(input);
int[] memory = intCode.ToArray();
int part1 = Run(memory, 12, 2);
solution.SubmitPart1(part1);
for (int noun = 0; noun < 100; noun++)
{
for (int verb = 0; verb < 100; verb++)
{
// reinitialise memory to intcode
intCode.CopyTo(memory);
if (Run(memory, noun, verb) == 19690720)
{
int part2 = 100 * noun + verb;
solution.SubmitPart2(part2);
return;
}
}
}
ThrowHelper.ThrowException("Unable to find solution for part 2");
}
private static int Run(int[] memory, int noun, int verb)
{
memory[1] = noun;
memory[2] = verb;
int ip = 0;
while (memory[ip] != 99)
{
int a = memory[ip + 1];
int b = memory[ip + 2];
int c = memory[ip + 3];
switch (memory[ip])
{
case 1:
memory[c] = memory[b] + memory[a];
break;
case 2:
memory[c] = memory[b] * memory[a];
break;
}
ip += 4;
}
return memory[0];
}
}