aocc23

Advent of Code 2023
git clone git://www.tkruger.se/aocc23.git
Log | Files | Refs | README

uppgb.c (1372B)


      1 #include "common.h"
      2 
      3 static int get_digit(const char *c) {
      4   if (*c == '\0')
      5     return -1;
      6 
      7   if (('0' <= c[0]) && (c[0] <= '9'))
      8     return (int)(c[0] - '0');
      9 
     10   if (strncmp(c, "one", 3) == 0)
     11     return 1;
     12   if (strncmp(c, "two", 3) == 0)
     13     return 2;
     14   if (strncmp(c, "three", 5) == 0)
     15     return 3;
     16   if (strncmp(c, "four", 4) == 0)
     17     return 4;
     18   if (strncmp(c, "five", 4) == 0)
     19     return 5;
     20   if (strncmp(c, "six", 3) == 0)
     21     return 6;
     22   if (strncmp(c, "seven", 5) == 0)
     23     return 7;
     24   if (strncmp(c, "eight", 5) == 0)
     25     return 8;
     26   if (strncmp(c, "nine", 4) == 0)
     27     return 9;
     28 
     29   return -1;
     30 }
     31 
     32 static int get_first_digit(const char *c) {
     33   const char *cur = c;
     34   int digit;
     35 
     36   while (*cur != '\0') {
     37     digit = get_digit(cur);
     38     if (digit != -1)
     39       return digit;
     40     cur++;
     41   }
     42 
     43   return -1;
     44 }
     45 
     46 static int get_last_digit(const char *str) {
     47   size_t len = strnlen(str, 500);
     48   const char *cur = str + len;
     49   int digit;
     50 
     51   while (cur >= str) {
     52     digit = get_digit(cur);
     53     if (digit != -1)
     54       return digit;
     55     cur--;
     56   }
     57 
     58   return -1;
     59 }
     60 
     61 int main(int argc, char **argv) {
     62   char **lines;
     63   size_t nlines = readlines(&lines, "input");
     64 
     65   size_t i;
     66   int first, last;
     67   int x = 0;
     68   for (i = 0; i < nlines; i++) {
     69     first = get_first_digit(lines[i]);
     70     last = get_last_digit(lines[i]);
     71     x += first * 10 + last;
     72   }
     73 
     74   printf("%d\n", x);
     75 }