DEV Community

Discussion on: Advent of Code 2019 Solution Megathread - Day 9: Sensor Boost

Collapse
 
neilgall profile image
Neil Gall • Edited

Well that was tough! The new requirements revealed a few deficiencies with my IntCode emulator. My addressing modes were a mess for writes, but somehow made it this far anyway. The need to expand the memory on demand meant a substantial refactor. I also had to use a nonstandard (but widely supported) __int128 data type to support the big numbers required.

Printing large numbers is also lacking support in the C standard library. I had to cut a couple of corners...

char *print_opcode(opcode n) {
    static char str[50];
    if (n == 0)
        return "0";
    else {
        char *s = str + sizeof(str)-1;
        int negative = 0;
        opcode x = n;
        if (x < 0) {
            negative = 1;
            x = -x; // eek, minimum negative value edge case
        }
        for (*--s = '\0'; x != 0 && s != str; x /= 10) {
            *--s = '0' + (x % 10);
        }
        if (negative) 
            *--s = '-';
        return s; // eek, not thread safe
    }
}

As part of my debugging I had it trace the execution using made-up assembly language:

Part 1
0000             1102  mul 34463338,34463338
0004             1007   lt 1187721666102244,34463338
0008             1005  jnz 0,53
0011             1101  add 0,3
0015              109 base 988
0017              209 base 3
0019                9 base 3
0021              209 base 3
0023              209 base 3
0025              203   in 1
0027             1008   eq 1,1
0031             1005  jnz 1,65
0065             1102  mul 32,1
0069             1101  add 0,500
0073             1101  add 0,636
0077             1102  mul 36,1
0081             1101  add 0,29
0085             1102  mul 864,1
0089             1102  mul 21,1

One advantage of using C is speed though. We were warned it might take time to run but the tests and both parts of my implementation run in 84 milliseconds!

Full code here. I've enjoyed my return to C programming but I'm quietly hoping for something using a high-level language tomorrow!