aocc23

Advent of Code 2023
git clone git://www.tkruger.se/aocc23.git
Log | Files | Refs | README

uppga.c (1455B)


      1 #include "common.h"
      2 
      3 #define MAX_LINE 256
      4 
      5 static size_t readline_i64s(int64_t *out, const size_t max, char *line) {
      6   char *cp = line;
      7   size_t i = 0;
      8 
      9   while ((cp = sread_next_i64(&out[i], cp)) != NULL) {
     10     i++;
     11     if (i >= max)
     12       break;
     13   }
     14 
     15   return i;
     16 }
     17 
     18 static int allzeros(int64_t *x, size_t n) {
     19   size_t i;
     20   for (i = 0; i < n; i++) {
     21     if (x[i] != 0)
     22       return 0;
     23   }
     24   return 1;
     25 }
     26 
     27 int main(int argc, char **argv) {
     28   char **lines;
     29   size_t nlines = readlines(&lines, "input");
     30   size_t i, j, k;
     31 
     32   int64_t ln[MAX_LINE];
     33   size_t nln;
     34 
     35   int64_t summarum = 0;
     36   for (i = 0; i < nlines; i++) {
     37     nln = readline_i64s(ln, MAX_LINE, lines[i]);
     38     int64_t *diffs = malloc((nln + 1) * (nln + 1) * sizeof(*diffs));
     39 
     40     // row 0 is just input
     41     for (j = 0; j < nln; j++)
     42       diffs[j] = ln[j];
     43 
     44     j = 0;
     45     size_t cnln = nln;
     46     while (!allzeros(&diffs[j * (nln + 1)], cnln)) {
     47       j++;
     48       cnln--;
     49       for (k = 0; k < cnln; k++) {
     50         diffs[j * (nln + 1) + k] =
     51             diffs[(j - 1) * (nln + 1) + k + 1] - diffs[(j - 1) * (nln + 1) + k];
     52       }
     53     }
     54 
     55     // goin' back up
     56     diffs[j * (nln + 1) + cnln] = 0;
     57     while (cnln < nln) {
     58       j--;
     59       cnln++;
     60       diffs[j * (nln + 1) + cnln] = diffs[(j + 1) * (nln + 1) + cnln - 1] +
     61                                     diffs[j * (nln + 1) + cnln - 1];
     62     }
     63     summarum += diffs[j * (nln + 1) + cnln];
     64 
     65     free(diffs);
     66   }
     67 
     68   printf("%lld\n", summarum);
     69 }