#include #include #include #include #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; }