-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnav.c
126 lines (112 loc) · 3.51 KB
/
nav.c
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
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char flip(char x) {
switch (x) {
case '(':
return ')';
case '[':
return ']';
case '{':
return '}';
case '<':
return '>';
default:
// aaaaaaa
return -1;
}
}
int compar(const void *a, const void *b) {
const long long *x = (const long long *) a;
const long long *y = (const long long *) b;
if (*x < *y) return -1;
if (*x == *y) return 0;
return 1;
}
int main(int argc, char **argv) {
char line[1024];
char stack[1024];
char len, stacklen, nlines = 0;
long long score[4] = {0, 0, 0, 0};
long long score2s[1024];
while (fgets(line, 1024, stdin) != NULL) {
len = strlen(line);
stacklen = 0;
int invalid = 0;
long long score2 = 0;
for (int i = 0; i < len; i++) {
switch (line[i]) {
case '(':
case '[':
case '{':
case '<':
stack[stacklen++] = line[i];
break;
case ')':
if (stack[stacklen-1] != '(' && !invalid) {
//puts("found invalid )");
score[0] += 1;
invalid = 1;
}
else stacklen--;
break;
case ']':
if (stack[stacklen-1] != '[' && !invalid) {
//puts("found invalid ]");
invalid = 1;
score[1] += 1;
}
else stacklen--;
break;
case '}':
if (stack[stacklen-1] != '{' && !invalid) {
//puts("found invalid }");
invalid = 1;
score[2] += 1;
}
else stacklen--;
break;
case '>':
if (stack[stacklen-1] != '<' && !invalid) {
//puts("found invalid >");
invalid = 1;
score[3] += 1;
}
else stacklen--;
break;
default:
goto EOL;
}
}
EOL:
if (stacklen > 0 && !invalid) {
for (int i = stacklen-1; i >= 0; i--) {
line[stacklen-1-i] = flip(stack[i]);
}
line[stacklen] = '\0';
for (int i = 0; i < stacklen; i++) {
score2 *= 5;
switch (line[i]) {
case '>':
score2 += 1;
case '}':
score2 += 1;
case ']':
score2 += 1;
case ')':
score2 += 1;
break;
default:
goto EOL2;
}
}
EOL2:
//printf("completion = %s (%lld)\n", line, score2);
score2s[nlines++] = score2;
}
}
qsort(score2s, nlines, sizeof(score2s[0]), compar);
printf("part 1 saw... ( %lld [ %lld { %lld < %lld; score = %lld\n", score[0], score[1], score[2], score[3], score[0] * 3 + score[1] * 57 + score[2] * 1197 + score[3] * 25137);
printf("part 2 median score = %lld\n", score2s[nlines / 2]);
}