Index: aoc2024.c ================================================================== --- aoc2024.c +++ aoc2024.c @@ -4,15 +4,27 @@ #include #include "aocutils.h" void aoc202403(char *data, [[maybe_unused]] size_t len) { - int sumproducts = 0, term[2]; + int sumproducts = 0, sumproducts2 = 0, term[2]; char *rest = data; + char *doleft = data; + char *dorite = strstr(data + 1, "do()"); + char *dontleft = data; + char *dontrite = strstr(dontleft + 1, "don't()"); for (;;) { char *mul = strstr(rest, "mul("); if (mul) { + while (dorite && (mul > dorite)) { + doleft = dorite; + dorite = strstr(dorite + 1, "do()"); + } + while (dontrite && (mul > dontrite)) { + dontleft = dontrite; + dontrite = strstr(dontrite + 1, "don't()"); + } rest = mul + 4; if (isdigit((unsigned char)rest[0])) { char *err; term[0] = (int)strtol(rest, &err, 10); if (*err == ',') { @@ -19,10 +31,11 @@ if (isdigit((unsigned char)err[1])) { rest = err + 1; term[1] = (int)strtol(rest, &err, 10); if (*err == ')') { sumproducts += term[0] * term[1]; + sumproducts2 += (doleft >= dontleft) * (term[0] * term[1]); rest = err + 1; } } } } @@ -29,10 +42,11 @@ } else { break; } } printf("The sum of the products is {%d}.\n", sumproducts); + printf("The sum of the products with conditionals is {%d}.\n", sumproducts2); } static int safereport(int *v, int nv) { int dir = 1; // ascending if (v[0] > v[1]) dir = -1; // descending