QUOTE: Never too old to chase dreams.

aoc_2023_1_1.c - aoc - Advent of Code challenges

aoc

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

aoc_2023_1_1.c (1036B)


      1 #include <stdio.h>
      2 #include <stdlib.h>
      3 #include <string.h>
      4 #include <ctype.h>
      5 
      6 #define MAX_DIGITS 100
      7 
      8 typedef struct {
      9   int count;
     10   char digits[MAX_DIGITS];
     11 } line_t;
     12 
     13 long perform(char *data) {
     14   (void) data;
     15   int len = strlen(data);
     16   int size = 0;
     17   for (int i = 0; i < len; i++) {
     18     char c = data[i];
     19     if (c == '\n') {
     20       size++;
     21     }
     22   }
     23   int idx = 0;
     24   line_t lines[size];
     25   lines[idx] = (line_t) { 0, {0} };
     26   for (int i = 0; i < len; i++) {
     27     char c = data[i];
     28     if (isdigit(c)) {
     29       line_t *line = &lines[idx];
     30       line->digits[line->count++] = c;
     31     }
     32     if (c == '\n') {
     33       idx++;
     34       lines[idx] = (line_t) { 0, {0} };
     35     }
     36   }
     37   int sum = 0;
     38   for (int i = 0; i < idx; i++) {
     39     line_t *line = &lines[i];
     40     if (line->count == 0) {
     41       continue;
     42     }
     43     char set = line->digits[0];
     44     char end = set;
     45     if (line->count > 1) {
     46       end = line->digits[line->count - 1];
     47     }
     48     char str[2] = { set, end };
     49     int digit = strtol(str, NULL, 10);
     50     sum += digit;
     51   }
     52   return sum;
     53 }