-
Notifications
You must be signed in to change notification settings - Fork 10
/
Day18.cs
117 lines (104 loc) · 2.84 KB
/
Day18.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
108
109
110
111
112
113
114
115
116
117
using System;
using System.Runtime.CompilerServices;
using AdventOfCode.CSharp.Common;
namespace AdventOfCode.CSharp.Y2020.Solvers;
public class Day18 : ISolver
{
public static void Solve(ReadOnlySpan<byte> input, Solution solution)
{
long part1 = 0;
long part2 = 0;
// initialise a stack and stack pointer for both parts
// we put -1 on top of the stack to represent a bad value
long[] stack1 = new long[64];
stack1[0] = -1;
int sp1 = 0;
long[] stack2 = new long[128];
stack2[0] = -1;
int sp2 = 0;
foreach (byte c in input)
{
if (c == '\n')
{
// for part 1 the stack will only have one item which is the answer
part1 += stack1[1];
// for part 2 the stack will looks like [-1, n1, *, n2, *, n3, * n4]
// so multiply every second number
long p2 = 1;
for (int i = 1; i <= sp2; i += 2)
p2 *= stack2[i];
part2 += p2;
// reset the stack pointers
sp1 = 0;
sp2 = 0;
}
else if (c != ' ')
{
ProcessCharPart1(c, ref stack1, ref sp1);
ProcessCharPart2(c, ref stack2, ref sp2);
}
}
solution.SubmitPart1(part1);
solution.SubmitPart2(part2);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void ProcessCharPart1(byte c, ref long[] stack, ref int sp)
{
long n;
if (c == ')')
{
n = stack[sp--];
sp--; // pop the '(' off the stack
}
else
{
n = c - '0';
}
if (n >= 0)
{
switch (stack[sp])
{
case '+' - '0':
sp--; // pop the '+' off the stack
stack[sp] += n;
break;
case '*' - '0':
sp--; // pop the '*' off the stack
stack[sp] *= n;
break;
default:
stack[++sp] = n;
break;
}
}
else
{
stack[++sp] = n;
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void ProcessCharPart2(byte c, ref long[] stack, ref int sp)
{
long n;
if (c == ')')
{
n = stack[sp--];
while (stack[sp--] != '(' - '0')
{
n *= stack[sp--];
}
}
else
{
n = c - '0';
}
if (n >= 0 && stack[sp] == '+' - '0')
{
stack[--sp] += n;
}
else
{
stack[++sp] = n;
}
}
}