QUOTE: Never too old to chase dreams.

aoc_2024_1_2.c - aoc - Advent of Code challenges

aoc

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

aoc_2024_1_2.c (906B)


      1 #include <stdlib.h>
      2 #include <string.h>
      3 #include <ctype.h>
      4 
      5 int compare_num(const void *a, const void *b) {
      6   return (*(int *) a) - (*(int *) b);
      7 }
      8 
      9 long perform(char *data) {
     10   int len = strlen(data);
     11   int size = 0;
     12   for (int i = 0; i < len; i++) {
     13     char c = data[i];
     14     if (c == '\n') {
     15       size++;
     16     }
     17   }
     18   int lft[size];
     19   int rgt[size];
     20   int odd = 0;
     21   int ln = 0;
     22   for (int i = 0; i < len;) {
     23     char c = data[i];
     24     if (isdigit(c)) {
     25       char *end = NULL;
     26       int num = strtol(data + i, &end, 10);
     27       odd ? (rgt[ln] = num) : (lft[ln] = num);
     28       odd = !odd;
     29       i += end - (data + i);
     30       continue;
     31     }
     32     if (c == '\n') {
     33       ln++;
     34     }
     35     i++;
     36   }
     37   int sum = 0;
     38   for (int i = 0; i < size; i++) {
     39     int count = 0;
     40     for (int j = 0; j < size; j++) {
     41       if (lft[i] == rgt[j]) {
     42         count++;
     43       }
     44     }
     45     sum += lft[i] * count;
     46   }
     47   return sum;
     48 }