Day 2: Fulminating Farmland

Megathread guidelines

  • Keep top level comments as only solutions, if you want to say something other than a solution put it in a new post. (replies to comments can be whatever)
  • You can send code in code blocks by using three backticks, the code, and then three backticks or use something such as https://topaz.github.io/paste/ if you prefer sending it through a URL

FAQ

  • Hugh@programming.dev
    link
    fedilink
    arrow-up
    3
    ·
    edit-2
    1 day ago

    C

    Based this on other solutions posted here.

    Usage:

    $ gcc main.c
    $ ./a.out input
    
    Part 1 solution
    #include <stdio.h>
    
    int get_index(char c)
    {
            int index;
            switch (c) {
                    case 'r':
                            index = 0;
                            break;
                    case 'o':
                            index = 1;
                            break;
                    case 'y':
                            index = 2;
                            break;
                    case 'g':
                            index = 3;
                            break;
                    case 'b':
                            index = 4;
                            break;
                    case 'v':
                            index = 5;
                            break;
            }
            return index;
    }
    
    int main(int argc, char** argv)
    {
            int t[6][6] = {
                    {6, 1, 2, 3, 4, 5},
                    {5, 6, 1, 2, 3, 4},
                    {4, 5, 6, 1, 2, 3},
                    {3, 4, 5, 6, 1, 2},
                    {2, 3, 4, 5, 6, 1},
                    {1, 2, 3, 4, 5, 6}
            };
            FILE *fp = fopen(argv[1], "r");
    
            int cur;
            int ch = 'r';
            int next = get_index(ch);
            int dist = 0;
    
            while (true) {
                    ch = fgetc(fp);
                    if (ch == EOF || ch == '\n') break;
                    cur = next;
                    next = get_index(ch);
                    dist += t[cur][next];
            }
            fclose(fp);
            printf("Distance travelled is: %i\n", dist);
            return 0;
    }
    

    Tried to keep it as small as possible, so obvious issues like not checking argc and not checking for letters other than roygbv. Which is pretty cursed because index is uninitialised, so get_index returns garbage, then t[cur][next] indexes into more garbage.

    • CameronDev@programming.devOPM
      link
      fedilink
      arrow-up
      2
      ·
      1 day ago

      Pretty standard for aoc to not check for invalid inputs, and just write just enough code to get the result. Indexing off into the weeds would be very frustrating to debug though if it didnt crash :D