aoc

Advent of code
git clone https://codeberg.org/night0721/aoc
Log | Files | Refs

2.c (1597B)


      1 #include "../../util.h"
      2 
      3 #include <stdio.h>
      4 #include <string.h>
      5 #include <stdlib.h>
      6 
      7 typedef struct {
      8     char *name;
      9     char* value;
     10 } number;
     11 
     12 int main() {
     13     FILE *inputfile = fopen("./input", "r");
     14     char *line = malloc(sizeof(char) * 100);
     15     number numbers[9];
     16     char *names[9] = { "one", "two", "three", "four", "five", "six", "seven", "eight", "nine" };
     17     char *values[9] = { "on1e", "tw2o", "th3ree", "fo4ur", "fi5ve", "si6x", "se7ven", "ei8ght", "ni9ne" }; 
     18     for (int k = 0; k < 9; k++) {
     19         numbers[k].name = names[k];
     20         numbers[k].value = values[k];
     21     }
     22     int sum = 0;
     23     size_t len = 0;
     24     ssize_t read;
     25     if (inputfile == NULL) {
     26         printf("Input file not found. Exiting.");
     27         exit(1);
     28     }
     29     while (fgets(line, 100, inputfile)) {
     30         int length = strlen(line);
     31         char *cpline = malloc(sizeof(char) * 1024);
     32         strcpy(cpline, line);
     33         for (int i = 0; i < 9; i++) {
     34             char *name = numbers[i].name;
     35             
     36             char *value = numbers[i].value;
     37             replace(cpline, name, value);
     38         }
     39         char *concat = malloc(sizeof(char) * strlen(cpline));
     40         for (int j = 0; j < strlen(cpline) - 1; j++) {
     41             int currentChar = (int) cpline[j];
     42             if (currentChar >= '0' && currentChar <= '9') {
     43                 concat[strlen(concat)] = cpline[j];
     44             }
     45         }
     46         char trimmed[3] = { 0 };
     47         trimmed[0] = concat[0];
     48         trimmed[1] = concat[strlen(concat) - 1];
     49         sum += atoi(trimmed);
     50     }
     51     fclose(inputfile);
     52     printf("%d\n", sum); 
     53 }