aoc_2023_1_2.c (1477B)
1 #include <stdio.h> 2 #include <stdlib.h> 3 #include <string.h> 4 #include <ctype.h> 5 6 #define NELEMS(x) (int) (sizeof(x) / sizeof((x)[0])) 7 #define MAX_DIGITS 100 8 9 typedef struct { 10 int count; 11 char digits[MAX_DIGITS]; 12 } line_t; 13 14 const char *DIGITS[9] = { "one", "two", "three", "four", "five", "six", "seven", "eight", "nine" }; 15 16 long perform(char *data) { 17 (void) data; 18 int len = strlen(data); 19 int size = 0; 20 for (int i = 0; i < len; i++) { 21 char c = data[i]; 22 if (c == '\n') { 23 size++; 24 } 25 } 26 int idx = 0; 27 line_t lines[size]; 28 lines[idx] = (line_t) { 0, {0} }; 29 for (int i = 0; i < len; i++) { 30 char c = data[i]; 31 if (isdigit(c)) { 32 line_t *line = &lines[idx]; 33 line->digits[line->count++] = c; 34 } 35 for (int j = 0; j < NELEMS(DIGITS); j++) { 36 const char *digit = DIGITS[j]; 37 int digit_len = strlen(digit); 38 if (strncmp(data + i, digit, digit_len) == 0) { 39 line_t *line = &lines[idx]; 40 line->digits[line->count++] = '1' + j; 41 break; 42 } 43 } 44 if (c == '\n') { 45 idx++; 46 lines[idx] = (line_t) { 0, {0} }; 47 } 48 } 49 int sum = 0; 50 for (int i = 0; i < idx; i++) { 51 line_t *line = &lines[i]; 52 if (line->count == 0) { 53 continue; 54 } 55 char set = line->digits[0]; 56 char end = set; 57 if (line->count > 1) { 58 end = line->digits[line->count - 1]; 59 } 60 char str[2] = { set, end }; 61 int digit = strtol(str, NULL, 10); 62 sum += digit; 63 } 64 return sum; 65 }