QUOTE: Be the change, make a difference.

aoc_2024_9_1.c - aoc - Advent of Code challenges

aoc

Advent of Code challenges
git clone git@soophie.de:/srv/git/aoc
log | files | refs

aoc_2024_9_1.c (1082B)


      1 #include <string.h>
      2 
      3 
      4 #define DISKSPACE_SIZE 100000
      5 #define PARTITION_SIZE 10000
      6 
      7 typedef struct {
      8   int id;
      9   int idx;
     10   size_t len;
     11 } part_t;
     12 
     13 long perform(char *data) {
     14   size_t len = strlen(data);
     15   size_t size = 0;
     16   int id = 0;
     17   part_t *diskspace[DISKSPACE_SIZE] = { NULL };
     18   part_t parts[PARTITION_SIZE];
     19   for (size_t i = 0; i < len; i++) {
     20     if (data[i] == '\n') {
     21       break;
     22     }
     23     int num = data[i] - '0';
     24     if (i % 2 == 0) {
     25       part_t part = {
     26         .id = id,
     27         .idx = size,
     28         .len = num,
     29       };
     30       parts[id] = part;
     31       for (size_t j = 0; j < part.len; j++) {
     32         diskspace[part.idx + j] = &parts[id];
     33       }
     34       id++;
     35     }
     36     size += num;
     37   }
     38   size_t end = size;
     39   for (size_t i = 0; i <= end; i++) {
     40     if (diskspace[i] == NULL) {
     41       part_t *part = NULL;
     42       while (end > i && part == NULL) {
     43         part = diskspace[end];
     44         end--;
     45       }
     46       diskspace[i] = part;
     47     }
     48   }
     49   long sum = 0;
     50   for (size_t i = 0; i <= end; i++) {
     51     part_t *part = diskspace[i];
     52     sum += i * part->id;
     53   }
     54   return sum;
     55 }