-
-
Save erikaderstedt/ade5f2d4a60a47fec344cfc350d6af64 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <stdlib.h> | |
#include <string.h> | |
#define ARG0 (modes[0] ? p[i+1] : p[p[i+1]]) | |
#define ARG1 (modes[1] ? p[i+2] : p[p[i+2]]) | |
int run_program(int *program, int length, int input) { | |
int *p = (int*)calloc(length, sizeof(int)); | |
memcpy(p, program, sizeof(int)*length); | |
int i = 0, output = 0; | |
while (p[i] != 99) { | |
int modes[4] = { 100,1000,10000,10000}; | |
int instruction = p[i] % 100; | |
for (size_t j = 0; j < 4; j++) modes[j] = (p[i] / modes[j]) % 10; | |
switch (instruction) { | |
case 1: p[p[i+3]] = ARG0 + ARG1; i += 4; break; | |
case 2: p[p[i+3]] = ARG0 * ARG1; i += 4; break; | |
case 7: p[p[i+3]] = (ARG0 < ARG1) ? 1 : 0; i += 4; break; | |
case 8: p[p[i+3]] = (ARG0 == ARG1) ? 1 : 0; i += 4; break; | |
case 3: p[p[i+1]] = input; i += 2; break; | |
case 4: output = ARG0; i += 2; break; | |
case 5: i = (ARG0 != 0) ? ARG1 : (i+3); break; | |
case 6: i = (ARG0 == 0) ? ARG1 : (i+3); break; | |
default: fprintf(stderr, "Invalid opcode %d.\n", p[i]); exit(1); | |
} | |
} | |
free(p); | |
return output; | |
} | |
int main(int argc, char **argv) { | |
int a[1024], i = 0; | |
FILE *fp = fopen(argv[1], "r"); | |
while(fscanf(fp, "%d,", a + i++) > 0); | |
fclose(fp); | |
i--; | |
printf("Pt 1: %d\n", run_program(a, i, 1)); | |
printf("Pt 2: %d\n", run_program(a, i, 5)); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment