summaryrefslogtreecommitdiff
path: root/Advent-of-Code-2022/aoc-1/main.c
diff options
context:
space:
mode:
authorkartofen <mladenovnasko0@gmail.com>2022-12-02 18:53:27 +0200
committerkartofen <mladenovnasko0@gmail.com>2022-12-02 18:53:27 +0200
commit41085185b9a69e455a72d6beed8f29c52967d21d (patch)
treeeff276573bef8a50b312045270b36e328d95a7a5 /Advent-of-Code-2022/aoc-1/main.c
parent4e9132b983c771d3e70d5a6b8bcdfdb1fead81fa (diff)
add 2022
Diffstat (limited to 'Advent-of-Code-2022/aoc-1/main.c')
-rw-r--r--Advent-of-Code-2022/aoc-1/main.c75
1 files changed, 75 insertions, 0 deletions
diff --git a/Advent-of-Code-2022/aoc-1/main.c b/Advent-of-Code-2022/aoc-1/main.c
new file mode 100644
index 0000000..7cb961e
--- /dev/null
+++ b/Advent-of-Code-2022/aoc-1/main.c
@@ -0,0 +1,75 @@
+#include <stdio.h>
+#include <stdlib.h>
+#include <limits.h>
+
+#if 0
+ #define FILENAME "sample.txt"
+#else
+ #define FILENAME "input.txt"
+#endif
+
+int biggest[3];
+
+int bigger(int val)
+{
+ for(int i = 2; i >= 0; i--)
+ if(val > biggest[i]) return i;
+ return -1;
+}
+
+void shift(int n, int val)
+{
+ for(int i = 1; i <= n; i++)
+ biggest[i-1] = biggest[i];
+
+ biggest[n] = val;
+}
+
+void check(int val)
+{
+ int b = bigger(val);
+ if(b != -1)
+ shift(b, val);
+}
+
+void parse()
+{
+ FILE *fp = fopen(FILENAME, "r");
+ if(!fp) {
+ fprintf(stderr, "ERROR: Could not open file %s\n", FILENAME);
+ exit(1);
+ }
+
+ char line[256];
+ int sum = 0;
+ while(fgets(line, sizeof(line), fp) != NULL)
+ {
+ if(line[0] == '\n') {
+ check(sum);
+ sum = 0;
+ }
+
+ sum += atoi(line);
+ }
+ check(sum); // the file does not end in a newline
+
+ fclose(fp);
+}
+
+int main(void)
+{
+ for(int i = 0; i < 3; i++)
+ biggest[i] = INT_MIN;
+
+ parse();
+
+ int sum = 0;
+ for(int i = 0; i < 3; i++) {
+ printf("%d\n", biggest[i]);
+ sum += biggest[i];
+ }
+
+ printf("\n%d\n", sum);
+
+ return 0;
+}