aocc23

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

uppgb.c (1215B)


      1 #include "common.h"
      2 
      3 static inline void gravitize_all_ind(uint8_t *ind, brick_t *bricks,
      4                                      const size_t n) {
      5   // assume sorted by l.b. on z, increasingly
      6   size_t i;
      7   memset(ind, 0, n);
      8 
      9   for (i = 0; i < n; i++) {
     10     while (may_gravitize(&bricks[i], bricks, i)) {
     11       gravitize(&bricks[i]);
     12       ind[i] = 1;
     13     }
     14   }
     15 }
     16 
     17 static uint64_t remcnt(brick_t *bricks, size_t n) {
     18   size_t i, j;
     19   brick_t b[n - 1];
     20   uint8_t ind[n - 1];
     21   uint64_t fallen;
     22   uint64_t tot = 0;
     23 
     24   for (i = 0; i < n; i++) {
     25     // copy all but brick i
     26     size_t jc = 0;
     27     for (j = 0; j < n; j++) {
     28       if (j != i) {
     29         b[jc] = bricks[j];
     30         jc++;
     31       }
     32     }
     33 
     34     // gravitize all
     35     gravitize_all_ind(ind, b, n - 1);
     36 
     37     // count number of fallen
     38     fallen = 0;
     39     for (j = 0; j < n - 1; j++) {
     40       if (ind[j])
     41         fallen++;
     42     }
     43 
     44     tot += fallen;
     45   }
     46 
     47   return tot;
     48 }
     49 
     50 int main(int argc, char **argv) {
     51   char **lines;
     52   size_t nlines = readlines(&lines, "input");
     53 
     54   brick_t bricks[nlines];
     55   read_bricks(bricks, lines, nlines);
     56   sort_bricks(bricks, nlines);
     57   gravitize_all(bricks, nlines);
     58 
     59   uint64_t count = remcnt(bricks, nlines);
     60   printf("%lld\n", count);
     61 }