summaryrefslogtreecommitdiff
path: root/Advent-of-Code-2020/AOC-5/main.c
diff options
context:
space:
mode:
authorkartofen <mladenovnasko0@gmail.com>2022-07-31 20:12:50 +0300
committerkartofen <mladenovnasko0@gmail.com>2022-07-31 20:12:50 +0300
commit1d96c68c66ba5648d1dd4d8ff2976fc97eea8a14 (patch)
tree42b2d354728e724b129e6ac8c7596243519080cc /Advent-of-Code-2020/AOC-5/main.c
parent48966f12832ac97228132e56fb3159099f3e466e (diff)
2020 days 4 and 5
Diffstat (limited to 'Advent-of-Code-2020/AOC-5/main.c')
-rw-r--r--Advent-of-Code-2020/AOC-5/main.c137
1 files changed, 137 insertions, 0 deletions
diff --git a/Advent-of-Code-2020/AOC-5/main.c b/Advent-of-Code-2020/AOC-5/main.c
new file mode 100644
index 0000000..2634753
--- /dev/null
+++ b/Advent-of-Code-2020/AOC-5/main.c
@@ -0,0 +1,137 @@
+#include <stdio.h>
+#include <stdlib.h>
+#include <assert.h>
+
+#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;
+}