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
|
#include <stdio.h>
#include <stdlib.h>
int
check_clock(int c, int X) {
switch (c+1) {
case 20:
case 60:
case 100:
case 140:
case 180:
case 220:
return (c+1) * X;
default:
return 0;
}
}
void
draw(int c, int X) {
int p = (c) % 40;
if (p == 0 && c != 0)
printf("\n");
if ((X-1) % 40 == p ||
(X) % 40 == p ||
(X+1) % 40 == p)
printf("#");
else
printf(".");
}
int
main(int argc, char **argv) {
char *buf = NULL;
size_t buflen = 0;
ssize_t n;
FILE *f;
int X = 1;
int clock = 0;
int total = 0;
if (argc != 2) {
fprintf(stderr, "usage: %s input\n", argv[0]);
return 1;
}
f = fopen(argv[1], "r");
if (f == NULL) {
perror(argv[1]);
return 1;
}
draw(clock, X);
while ((n = getline(&buf, &buflen, f)) != -1) {
if (buf[n - 1] == '\n') {
buf[n - 1] = '\0';
n--;
}
if (buf[0] == 'a') {
int a;
if (sscanf(buf+5, "%d", &a) != 1) {
perror("sscanf");
return 1;
}
clock++;
total += check_clock(clock, X);
draw(clock, X);
X += a;
}
clock++;
total += check_clock(clock, X);
draw(clock, X);
}
printf("Part A: %d\n", total);
free(buf);
fclose(f);
return 0;
}
|