chore: initial commit
This commit is contained in:
51
day_1.c
Normal file
51
day_1.c
Normal file
@@ -0,0 +1,51 @@
|
||||
//
|
||||
// Created by Lennart on 02/12/2023.
|
||||
//
|
||||
|
||||
#include <stdio.h>
|
||||
#include "main.h"
|
||||
|
||||
int read_line(FILE *f);
|
||||
|
||||
int day_1() {
|
||||
FILE *f = fopen("day_1.txt", "r");
|
||||
if(f == NULL) {
|
||||
printf("Error! Missing input file!");
|
||||
return -1;
|
||||
}
|
||||
|
||||
int sum = 0;
|
||||
while(!feof(f)) {
|
||||
sum += read_line(f);
|
||||
}
|
||||
|
||||
fclose(f);
|
||||
printf("Result: %i\n", sum);
|
||||
return 0;
|
||||
}
|
||||
|
||||
// Read all digits form the next line in a file
|
||||
int read_line(FILE *f) {
|
||||
int first = -1, last = 10; // Use first=-1 to detect unset value and last=10 to return 0 (-10 + 10) when no values are set
|
||||
char buffer[16];
|
||||
int digit;
|
||||
do {
|
||||
fgets(&buffer[0], 16, f);
|
||||
for(int i = 0; i < 16; i++) {
|
||||
if(buffer[i] == '\n') {
|
||||
goto result;
|
||||
} else if(buffer[i] == 0) {
|
||||
break; // End of buffer
|
||||
}
|
||||
if(sscanf(&buffer[i], "%1d", &digit) == 1) { // NOLINT(*-err34-c)
|
||||
if(first == -1) {
|
||||
first = digit;
|
||||
}
|
||||
last = digit;
|
||||
}
|
||||
}
|
||||
} while(!feof(f));
|
||||
|
||||
result:
|
||||
return first * 10 + last;
|
||||
}
|
||||
Reference in New Issue
Block a user