#include #include #include #if 0 #define PART part1 #else #define PART part2 #endif #if 0 #define FILENAME "sample.txt" #else #define FILENAME "input.txt" #endif int sum = 0; int char_to_index(char ch) { if(ch >= 'a') return ch - 'a'; return ch - 'A' + 26; } void part1(char *line) { int times_seen[56] = {0}; int leftest[56] = {0}; // rightest position of that character seen int rightest[56] = {0}; // leftest position of that character seen int len = strlen(line); len = (len % 2) ? len : len - 1; // fgets reads the new line and the last line has no newline for(int i = 0; i < len; i++) { int ch = char_to_index(line[i]); times_seen[ch]++; if(times_seen[ch] == 1) leftest[ch] = i; else rightest[ch] = i; if(times_seen[ch] > 1) if(leftest[ch] < len/2 && rightest[ch] >= len/2) { sum += ch + 1; break; } } } int gn = 0; int times_seen[56][3] = {0}; void part2(char *line) { for(int i = 0; line[i] != '\n' && line[i] != '\0'; i++) times_seen[char_to_index(line[i])][gn]++; gn++; if(gn == 3) { for(int j = 0; j < 56; j++) if(times_seen[j][0] && times_seen[j][1] && times_seen[j][2]) { sum += j + 1; break; } gn = 0; memset(times_seen, 0, sizeof(times_seen)); } } void parse() { FILE *fp = fopen(FILENAME, "r"); if(!fp) { fprintf(stderr, "ERROR: Could not open file: %s\n", FILENAME); exit(1); } char line[256]; while(fgets(line, sizeof(line), fp) != NULL) PART(line); fclose(fp); } int main(void) { parse(); printf("%d\n", sum); return 0; }