-
Notifications
You must be signed in to change notification settings - Fork 0
/
Day18.java
132 lines (109 loc) · 3.1 KB
/
Day18.java
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
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
package io.github.sirnikolai.days;
import io.github.sirnikolai.AbstractSolution;
import java.util.*;
public class Day18 extends AbstractSolution {
private int x = 0;
@Override
public void Part1(String input) {
String[] arr = input.split("\n");
long tally = 0;
for(String s : arr) {
x = 0;
tally += getResult(s);
}
System.out.println(tally);
}
private long getResult(String q) {
q = q.replaceAll(" ", "");
long tally = 0;
char sign = '+';
for( ;x < q.length(); x++) {
if(q.charAt(x) == ')') {
x++;
break;
}
if(q.charAt(x) == '(') {
x++;
tally = getResult(tally, getResult(q), sign);
x--;
continue;
}
if(Character.isDigit(q.charAt(x))) {
tally = getResult(tally, q.charAt(x) - '0', sign);
} else {
sign = q.charAt(x);
}
}
// System.out.println(tally);
return tally;
}
private long getResult(long tally, long val, char sign) {
switch (sign) {
case '+':
tally += val;
break;
case '-':
tally -= val;
break;
case '*':
tally *= val;
break;
}
return tally;
}
private long getResult2(String q) {
q = q.replaceAll(" ", "");
Stack<Long> tally = new Stack<>();
char sign = '+';
for( ;x < q.length(); x++) {
if(q.charAt(x) == ')') {
x++;
break;
}
if(q.charAt(x) == '(') {
x++;
long result = getResult2(q);
if(tally.isEmpty()) {
tally.push(result);
} else {
if(sign == '+') {
tally.push(tally.pop() + result);
} else {
tally.push(result);
}
}
x--;
continue;
}
if(Character.isDigit(q.charAt(x))) {
if(tally.isEmpty()) {
tally.push((long) (q.charAt(x) - '0'));
} else {
if(sign == '+') {
tally.push(tally.pop() + (q.charAt(x) - '0'));
} else {
tally.push((long) (q.charAt(x) - '0'));
}
}
} else {
sign = q.charAt(x);
}
}
long total = 1;
while(!tally.isEmpty()) {
total *= tally.pop();
}
return total;
}
@Override
public void Part2(String input) {
String[] arr = input.split("\n");
long tally = 0;
for(String s : arr) {
x = 0;
tally += getResult2(s);
// System.out.println(getResult2(s));
}
System.out.println(tally);
}
}