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
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#if 0
#define PART part1
#else
#define PART part2
#endif
#if 0
#define FILENAME "sample.txt"
#else
#define FILENAME "input.txt"
#endif
#define CMDS 2
char commands[CMDS][5] = {"noop", "addx"};
char cmdcycles[CMDS] = {1, 2};
int x = 1;
int cycles = 0;
int sum = 0;
void part1()
{
cycles++;
if((cycles+20) % 40 == 0) sum += cycles * x;
}
void part2()
{
int i = cycles % 40;
printf("%c", (x == i || x == i+1 || x == i-1) ? '#' : '.');
if(i == 39) printf("\n");
cycles++;
}
int parse_cmd(char *cmdstr)
{
for(int i = 0; i < CMDS; i++)
if(strncmp(commands[i], cmdstr, 4) == 0) return i;
return -1;
}
void parse()
{
FILE *fp = fopen(FILENAME, "r");
if(!fp) {
fprintf(stderr, "ERROR: Could not open file: %s\n", FILENAME);
exit(1);
}
char line[256];
while(fgets(line, sizeof(line), fp))
{
int cmd = parse_cmd(strtok(line, " "));
assert(cmd >= 0);
for(int i = 0; i < cmdcycles[cmd]; i++)
{
PART();
switch(cmd) {
case 0:
break;
case 1:
if(i == 1) x += atoi(strtok(NULL, " "));
break;
}
}
}
fclose(fp);
}
int main(void)
{
parse();
printf("%d\n", sum);
return 0;
}
|