aoc_2024_1_1.c (887B)
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 qsort(lft, size, sizeof(int), compare_num); 38 qsort(rgt, size, sizeof(int), compare_num); 39 int sum = 0; 40 for (int i = 0; i < size; i++) { 41 sum += abs(lft[i] - rgt[i]); 42 } 43 return sum; 44 }