QUOTE: Be someone’s rainbow today.

aoc

Advent of Code challenges

aoc_2024_7_1.c (1369B)


      1#include <stdio.h>
      2#include <stdlib.h>
      3#include <stdbool.h>
      4#include <ctype.h>
      5#include <string.h>
      6#include <math.h>
      7
      8#define VALUES_SIZE 25
      9#define OP_SIZE 2
     10
     11typedef enum {
     12  OP_ADD = '+',
     13  OP_MUL = '*',
     14} op_t;
     15
     16long perform(char *data) {
     17  size_t len = strlen(data);
     18  long sum = 0;
     19  long result;
     20  long values[VALUES_SIZE];
     21  int idx = 0;
     22  bool is_values = false;
     23  for (size_t i = 0; i < len;) {
     24    char c = data[i];
     25    if (c == '\n') {
     26      bool is_equal = false;
     27      int iter = pow(2, idx - 1);
     28      for (int i = 0; i < iter; i++) {
     29        long num = values[0];
     30        int k = 1;
     31        for (int j = idx - 1 - 1; j >= 0; j--) {
     32          op_t op = (i >> j) & 1 ? OP_ADD : OP_MUL;
     33          if (op == OP_ADD) {
     34            num += values[k];
     35          }
     36          if (op == OP_MUL) {
     37            num *= values[k];
     38          }
     39          k++;
     40        }
     41        if (num == result) {
     42          is_equal = true;
     43        }
     44      }
     45      if (is_equal) {
     46        sum += result;
     47      }
     48      idx = 0;
     49      is_values = false;
     50      i++;
     51      continue;
     52    }
     53    if (isdigit(c)) {
     54      char *end = NULL;
     55      long num = strtol(data + i, &end, 10);
     56      if (is_values) {
     57        values[idx++] = num;
     58      }
     59      else {
     60        result = num;
     61        is_values = true;
     62      }
     63      i += end - (data + i);
     64      continue;
     65    }
     66    i++;
     67  }
     68  return sum;
     69}