-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path03a.c
90 lines (69 loc) · 2.09 KB
/
03a.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
#include <assert.h>
#include <ctype.h> // isdigit
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h> // memset
#define NLINES 4
#define NMASK (NLINES - 1)
#define NCHARS 150
static bool issymbol(char c) {
return c != 0 && c != '.' && !isdigit(c);
}
static int64_t parse_part_numbers(const char above[NCHARS], const char current[NCHARS], const char below[NCHARS]) {
int64_t sum = 0;
int num = 0;
bool is_part = false;
for (int i = 1; i < NCHARS; ++i) {
if (isdigit(current[i])) {
num = num * 10 + (current[i] - '0');
is_part =
is_part ||
issymbol(above[i - 1]) ||
issymbol(above[i]) ||
issymbol(above[i + 1]) ||
issymbol(current[i - 1]) ||
issymbol(current[i + 1]) ||
issymbol(below[i - 1]) ||
issymbol(below[i]) ||
issymbol(below[i + 1]);
} else {
if (is_part) sum += num;
num = 0;
is_part = false;
}
}
return sum;
}
int main(void) {
char *line = NULL;
size_t ngetline = 0;
int64_t sum = 0;
int ir = 3;
int jr = 0;
int nchars = 0;
char schematic[NLINES][NCHARS] = {0};
while ((nchars = (int)getline(&line, &ngetline, stdin)) > 0) {
if (line[nchars - 1] == '\n') line[--nchars] = 0;
assert((nchars + 1) < (NCHARS - 1));
memcpy(&schematic[ir++ & NMASK][1], line, nchars); // start at 1 to skip the need for boundary checks
sum += parse_part_numbers(
schematic[jr & NMASK],
schematic[(jr + 1) & NMASK],
schematic[(jr + 2) & NMASK]
);
++jr;
}
for (int k = 0; k < NLINES; k++) {
memset(schematic[ir++ & NMASK], 0, NCHARS);
sum += parse_part_numbers(
schematic[jr & NMASK],
schematic[(jr + 1) & NMASK],
schematic[(jr + 2) & NMASK]
);
++jr;
}
free(line);
printf("%lld\n", sum);
return 0;
}