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
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
|
//#define _GNU_SOURCE
#include <regex.h>
#include <search.h>
#include <stdio.h>
#include <stdlib.h>
#define arrlen(x) (sizeof(x)/sizeof((x)[0]))
struct point {
int x;
int y;
int z;
};
int
point_cmp(struct point const * a, struct point const * b)
{
if (a->x != b->x)
return a->x - b->x;
if (a->y != b->y)
return a->y - b->y;
return a->z - b->z;
}
int
point_cmp_t(void const * a, void const * b)
{
return point_cmp(a, b);
}
// Get one of the faces of a cube
//
// x = left-right
// y = up-down
// z = front-back
//
// To uniquely identify the faces of a cube, we scale the cube by a factor of
// two, and then identify each face by the point at the face's center.
struct point *
cube_face(int x, int y, int z, int face)
{
struct point * f;
x *= 2;
y *= 2;
z *= 2;
switch (face) {
case 0: // Bottom face
x += 1;
z += 1;
break;
case 1: // Top face
x += 1;
y += 2;
z += 1;
break;
case 2: // Left face
y += 1;
z += 1;
break;
case 3: // Right face
x += 2;
y += 1;
z += 1;
break;
case 4: // Front face
x += 1;
y += 1;
break;
case 5: // Back face
x += 1;
y += 1;
z += 2;
break;
default:
return NULL;
}
if ((f = malloc(sizeof(struct point))) == NULL)
return NULL;
f->x = x;
f->y = y;
f->z = z;
return f;
}
int
main()
{
char buf[BUFSIZ];
regex_t cube;
regmatch_t coords[4];
void * faces = NULL;
int nfaces = 0;
if (regcomp(&cube, "(-?[[:digit:]]+),(-?[[:digit:]]+),(-?[[:digit:]]+)", REG_EXTENDED) != 0) {
fprintf(stderr, "Bad regex\n");
return -1;
}
while (fgets(buf, sizeof(buf), stdin)
&& regexec(&cube, buf, arrlen(coords), coords, 0) == 0)
{
int x, y, z, f;
x = atoi(buf + coords[1].rm_so);
y = atoi(buf + coords[2].rm_so);
z = atoi(buf + coords[3].rm_so);
for (f = 0; f < 6; ++f) {
struct point * face = cube_face(x, y, z, f);
struct point * exists = *((struct point **) tsearch(face, &faces, point_cmp_t));
if (exists == face) {
// Inserted new face
++nfaces;
}
else {
// Face already existed, so delete it
tdelete(face, &faces, point_cmp_t);
--nfaces;
free(face);
free(exists);
}
}
}
printf("Faces: %d\n", nfaces);
#ifdef _GNU_SOURCE
tdestroy(faces, free);
#endif
regfree(&cube);
return 0;
}
|