#include #include #include #if 0 #define PART_1 #else #define PART_2 #endif #if 0 #define FILE_PATH "example.txt" #define IDS 4 #else #define FILE_PATH "input.txt" #define IDS 908 #endif #define LOWER(min, max) ((max) - (((max) - (min))/2 + 1)) #define UPPER(min, max) (((min) + (max))/2 + 1) #define ROWS 128 #define COLUMNS 8 int highest_id = 0; int ids[IDS] = {0}; void process_pass(char *pass, int index) { int min_r = 0; int max_r = ROWS - 1; int min_c = 0; int max_c = COLUMNS - 1; for(int i = 0; i < 10; i++) { switch(pass[i]) { case 'F': max_r = LOWER(min_r, max_r); break; case 'B': min_r = UPPER(min_r, max_r); break; case 'L': max_c = LOWER(min_c, max_c); break; case 'R': min_c = UPPER(min_c, max_c); break; } } int id = min_r * 8 + min_c; #ifdef PART_1 (void)index; if(id > highest_id) highest_id = id; #endif #ifdef PART_2 assert(index < IDS); ids[index] = id; #endif } void parse() { FILE *fp = fopen(FILE_PATH, "r"); if(!fp) { fprintf(stderr, "ERROR: Could not open file: %s\n", FILE_PATH); exit(EXIT_FAILURE); } int i = 0; char line[256] = {0}; while(fgets(line, sizeof(line), fp) != NULL) { if(line[10] == '\n') line[10] = '\0'; process_pass(line, i); i++; } fclose(fp); } int find_id() { int your_seat; int seat_missing; for(int i = 0; i < IDS; i++) { your_seat = -1; seat_missing = 0; for(int j = 0; j < IDS; j++) { if(ids[i] == (ids[j] + 2)) { your_seat = ids[i] - 1; seat_missing = 1; for(int k = 0; k < IDS; k++) if(your_seat == ids[k]) seat_missing = 0; } } if(your_seat!= -1 && seat_missing != 0) return your_seat; } return -1; } void part_1() { printf("Highest boarding ID is %d\n", highest_id); } void part_2() { printf("Your id is: %d\n", find_id()); } int main(void) { parse(); #ifdef PART_1 part_1(); #endif #ifdef PART_2 part_2(); #endif return 0; }