QUOTE: Never too old to chase dreams.

aoc_2024_3_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_3_1.c (1022B)


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