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
|
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#define BUF_SIZE 8192
enum State {
FIRST_NUMBER,
DASH,
SECOND_NUMBER,
SPACE,
LETTER,
COLON,
SPACE2,
PASSWORD,
EOL,
EOI
};
struct state {
enum State s;
char letter;
int min;
int max;
int count;
};
char buffer[BUF_SIZE];
int get_digit(char c) {
if (c <= '9' && c >= '0') {
return c-'0';
}
}
void parse_byte(struct state *state, char c) {
switch (state->s) {
case PASSWORD:
password:
if (c == state->letter) {
state->count++;
} else if (c == '\n') {
state->s = EOL;
}
break;
case FIRST_NUMBER:
if (c == '-') {
state->s = DASH;
} else {
int digit = get_digit(c);
state->min *= 10;
state->min += digit;
}
break;
case DASH:
state->s = SECOND_NUMBER;
case SECOND_NUMBER:
if (c == ' ') {
state->s = SPACE;
} else {
int digit = get_digit(c);
state->max *= 10;
state->max += digit;
}
break;
case SPACE:
state->letter = c;
state->s = COLON;
break;
case COLON:
state->s = SPACE2;
break;
case SPACE2:
state->s = PASSWORD;
goto password;
}
}
int count_correct() {
int fd = open("input.txt", O_RDONLY);
struct state state;
state.s = FIRST_NUMBER;
state.min = 0;
state.max = 0;
state.letter = '\0';
state.count = 0;
int count = 0;
while (state.s != EOI) {
ssize_t bytes = read(fd, buffer, BUF_SIZE);
if (bytes < 0) {
printf("failed to read!\n");
exit(1);
} else if (bytes == 0) {
state.s = EOI;
}
for (int i = 0; i < bytes; i++) {
parse_byte(&state, buffer[i]);
if (state.s == EOL) {
if (state.count >= state.min && state.count <= state.max) {
count++;
}
state.s = FIRST_NUMBER;
state.min = 0;
state.max = 0;
state.letter = '\0';
state.count = 0;
}
}
}
return count;
}
int main() {
printf("%d\n", count_correct());
}
|