-
Notifications
You must be signed in to change notification settings - Fork 0
/
Day18.cs
98 lines (87 loc) · 2.25 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
using System;
using System.Collections.Generic;
using System.IO;
class Day18 {
public static int Solution1() {
long sum = 0;
foreach (string line in File.ReadLines("input18.txt")) {
Stack<long> values = new Stack<long>();
Stack<char> operators = new Stack<char>();
foreach (char c in line) {
switch (c) {
case ' ':
break;
case '(':
operators.Push(c);
break;
case ')':
char op;
while ((op = operators.Pop()) != '(') {
values.Push(Calc(values.Pop(), values.Pop(), op));
}
break;
case '+':
case '*':
if (operators.Count > 0 && operators.Peek() != '(') {
values.Push(Calc(values.Pop(), values.Pop(), operators.Pop()));
}
operators.Push(c);
break;
default:
values.Push(c - '0');
break;
}
}
while (operators.Count > 0) {
values.Push(Calc(values.Pop(), values.Pop(), operators.Pop()));
}
sum += values.Pop();
}
Console.WriteLine(sum);
return 0;
}
public static int Solution2() {
long sum = 0;
foreach (string line in File.ReadLines("input18.txt")) {
Stack<long> values = new Stack<long>();
Stack<char> operators = new Stack<char>();
foreach (char c in line) {
switch (c) {
case ' ':
break;
case '(':
operators.Push(c);
break;
case ')':
char op;
while ((op = operators.Pop()) != '(') {
values.Push(Calc(values.Pop(), values.Pop(), op));
}
break;
case '+':
if (operators.Count > 0 && operators.Peek() == '+') {
values.Push(Calc(values.Pop(), values.Pop(), operators.Pop()));
}
operators.Push(c);
break;
case '*':
while (operators.Count > 0 && operators.Peek() != '(') {
values.Push(Calc(values.Pop(), values.Pop(), operators.Pop()));
}
operators.Push(c);
break;
default:
values.Push(c - '0');
break;
}
}
while (operators.Count > 0) {
values.Push(Calc(values.Pop(), values.Pop(), operators.Pop()));
}
sum += values.Pop();
}
Console.WriteLine(sum);
return 0;
}
static long Calc(long a, long b, char op) => op == '+' ? a + b : a * b;
}