Finished day 1 in C!

This commit is contained in:
Steph 2022-12-01 21:02:00 +01:00
parent be61888c85
commit e742759626
5 changed files with 100 additions and 0 deletions

3
2021/1/.gitignore vendored Normal file
View File

@ -0,0 +1,3 @@
depth
depth2
input

11
2021/1/Makefile Normal file
View File

@ -0,0 +1,11 @@
.PHONY := all yeet
all: build run
build:
gcc -o depth depth.c
gcc -o depth2 depth2.c
run:
./depth
./depth2

28
2021/1/depth.c Normal file
View File

@ -0,0 +1,28 @@
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
int main() {
FILE *input = fopen("input", "r");
if(input == NULL) {
printf("oh noes couldn't open the input file lol\n");
return 1;
}
char line[255];
int count = 0, last_num = INT_MAX;
while(fgets(line, sizeof(line), input) != NULL) {
int cur_num = atoi(line);
count += cur_num > last_num;
last_num = cur_num;
}
fclose(input);
printf("There were %d measurements larger than the last.\n", count);
}

55
2021/1/depth2.c Normal file
View File

@ -0,0 +1,55 @@
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#define WINDOW_SIZE 3
int main() {
FILE *input = fopen("input", "r");
if(input == NULL) {
printf("oh noes couldn't open the input file lol\n");
return 1;
}
char line[255];
int index = 0, count = 0, last_num = INT_MAX;
int windows[WINDOW_SIZE][WINDOW_SIZE];
while(fgets(line, sizeof(line), input) != NULL) {
int cur_num = atoi(line),
cur_index = index % (WINDOW_SIZE);
// Put values diagonal into the 3x3 grid, like this
// A B C
// B C A
// C A B
for(int i=0; i<WINDOW_SIZE; i++){
int cur_col = (cur_index + i) % WINDOW_SIZE;
windows[i][cur_col] = cur_num;
}
index++;
if(index < WINDOW_SIZE) // skip first 3 values
continue;
// Calculate average for current column, e.g.
// A B C
// B C A
// C A B
// ^
int sum = 0;
for(int i=0; i<WINDOW_SIZE; i++)
sum += windows[cur_index][i];
count += sum > last_num;
last_num = sum;
}
fclose(input);
printf("There were %d measurements larger than the last.\n", count);
}

View File

@ -2,6 +2,9 @@
Heya! This is my advent of code repo (as you might have guessed). In here you'll find my solutions of the advent of code exercises.
# 2021
So similar to last year, a different language each day. Different though: I pick the language myself instead of using the little seeded ransomizer. Hopefully this helps with me finishing it when I am busy that day (by picking a language I already know).
## 2020