advent2019

Advent of Code 2019 (C99)
git clone git://bsandro.tech/advent2019
Log | Files | Refs | LICENSE

commit dbe8221ce0b2c9672dc92ef833e240bc0b821d16
parent 1abca040b7e39f5ab2f8fc5799071195442d866e
Author: bsandro <email@bsandro.tech>
Date:   Sun,  7 Dec 2025 01:44:27 +0200

Day 02

Diffstat:
Aday02.c | 83+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
1 file changed, 83 insertions(+), 0 deletions(-)

diff --git a/day02.c b/day02.c @@ -0,0 +1,83 @@ +#include <stdio.h> +#include <inttypes.h> +#include <string.h> + +#define MAX_LEN 256 + +typedef struct { + char data[16]; + int len; +} Buffer; + +typedef int Program[MAX_LEN]; + +int btoi(Buffer buf) { + int num = 0; + for (int i=0;i<buf.len;++i) num = num*10+buf.data[i]; + return num; +} + +void program_print(const Program prg) { + for (int i=0;i<MAX_LEN;++i) { + printf("%d,", prg[i]); + } + printf("\n"); +} + +int program_step(Program prg, int ip) { + int opcode = prg[ip]; + switch (opcode) { + case 1: { // addition + prg[prg[ip+3]] = prg[prg[ip+1]] + prg[prg[ip+2]]; + return ip+4; + } + case 2: { // multiplication + prg[prg[ip+3]] = prg[prg[ip+1]] * prg[prg[ip+2]]; + return ip+4; + } + case 99: return -1; // halt + } + return -2; +} + +int program_run(const Program prg1, int noun, int verb) { + Program prg = {0}; + memcpy(prg, prg1, MAX_LEN*sizeof(prg[0])); + int ip = 0; + prg[1] = noun; + prg[2] = verb; + for (ip=0; ip!=-1&&ip<MAX_LEN; ip=program_step(prg, ip)) { + if (ip==-2) { + printf("invalid opcode\n"); + return 0; + } + } + return prg[0]; +} + +int main(void) { + Program prg = {0}; + int ip = 0; + Buffer buf = {0}; + for (int c=getchar();c!=EOF;c=getchar()) { + if (c>='0'&&c<='9') { + buf.data[buf.len++] = c-'0'; + } else { + prg[ip++] = btoi(buf); + buf.len = 0; + } + } + int p1 = program_run(prg, 12, 2); + int p2 = 0; + for (int noun=0; noun<100; ++noun) { + for (int verb=0; verb<100; ++verb) { + if (program_run(prg, noun, verb) == 19690720) { + p2 = 100*noun+verb; + goto fin; + } + } + } + fin: + printf("p1: %d\np2: %d\n", p1, p2); + return 0; +}