QUOTE: Be the change, make a difference.

aoc_2024_3_2.c - aoc - Advent of Code challenges

aoc

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

aoc_2024_3_2.c (1259B)


      1 #include <stdio.h>
      2 #include <stdlib.h>
      3 #include <stdbool.h>
      4 #include <string.h>
      5 #include <ctype.h>
      6 
      7 #define OPS_SIZE 1000
      8 
      9 typedef struct {
     10   int a;
     11   int b;
     12 } op_t;
     13 
     14 long perform(char *data) {
     15   int len = strlen(data);
     16   int size = 0;
     17   op_t ops[OPS_SIZE];
     18   bool is_enabled = true;
     19   for (int i = 0; i < len;) {
     20     if (strncmp(data + i, "do()", 4) == 0) {
     21       is_enabled = true;
     22     }
     23     if (strncmp(data + i, "don't()", 7) == 0) {
     24       is_enabled = false;
     25     }
     26     // detect pattern: mul(\d,\d)
     27     // mul(
     28     if (strncmp(data + i, "mul(", 4) == 0) {
     29       i += 4;
     30       char *end = NULL;
     31       op_t *op = &ops[size];
     32       // \d
     33       if (!isdigit(data[i])) {
     34         continue;
     35       }
     36       op->a = strtol(data + i, &end, 10);
     37       i += end - (data + i);
     38       // ,
     39       if (data[i] != ',') {
     40         continue;
     41       }
     42       i++;
     43       // \d
     44       if (!isdigit(data[i])) {
     45         continue;
     46       }
     47       op->b = strtol(data + i, &end, 10);
     48       i += end - (data + i);
     49       // )
     50       if (data[i] != ')') {
     51         continue;
     52       }
     53       i++;
     54       if (is_enabled) {
     55         size++;
     56       }
     57       continue;
     58     }
     59     i++;
     60   }
     61   int sum = 0;
     62   for (int i = 0; i < size; i++) {
     63     op_t op = ops[i];
     64     sum += op.a * op.b;
     65   }
     66   return sum;
     67 }