3a.c (1936B)
1 #include <stdio.h> 2 #include <stdlib.h> 3 #include <string.h> 4 #include <errno.h> 5 6 int compare_char(const char *first, const char *second) { 7 return *first - *second; 8 } 9 10 int main(void) { 11 FILE *input = fopen("input", "r"); 12 char *line_in = NULL; 13 size_t buf_len; 14 unsigned int prio_sum = 0; 15 16 while (!feof(input)) { 17 if (getline(&line_in, &buf_len, input) != -1) { 18 size_t len = strlen(line_in); 19 if (len > 2 && line_in[len - 1] == '\n') { 20 // Truncate 21 line_in[len - 1] = 0; 22 len -= 1; 23 } 24 if (len % 2) { 25 fprintf(stderr, "Bad line!\n"); 26 exit(EXIT_FAILURE); 27 } 28 size_t half_len = (len / 2) + 1; 29 30 // Split the compartments 31 char *first_half = malloc(half_len); 32 char *second_half = malloc(half_len); 33 strncpy(first_half, line_in, half_len - 1); 34 strncpy(second_half, line_in + (half_len - 1), half_len - 1); 35 36 // Sort both sides 37 qsort(first_half, half_len - 1, sizeof(char), compare_char); 38 qsort(second_half, half_len - 1, sizeof(char), compare_char); 39 40 // Spin over the two compartments and find any duplicates 41 for (int i = 0, j = 0;i < half_len && j < half_len;i++) { 42 // Run to the end of the current run 43 while (i < (half_len - 1) && first_half[i] == first_half[i + 1]) 44 i++; 45 46 // Skip any characters less than first_half[i] 47 while (j < half_len && second_half[j] < first_half[i]) 48 j++; 49 50 if (first_half[i] == second_half[j]) { 51 char dup = first_half[i]; 52 if (dup >= 'a' && dup <= 'z') { 53 prio_sum += dup - 96; 54 } else { 55 prio_sum += dup - 38; 56 } 57 } 58 } 59 60 free(line_in); 61 line_in = NULL; 62 } else { 63 free(line_in); 64 if (errno) { 65 strerror(NULL); 66 exit(EXIT_FAILURE); 67 } 68 } 69 } 70 printf("Priority sum: %i\n", prio_sum); 71 72 fclose(input); 73 }