This commit is contained in:
2024-12-04 20:57:10 +01:00
parent 928218226b
commit 38d35082b0
3 changed files with 197 additions and 0 deletions

76
day-02-c/task1.c Normal file
View File

@@ -0,0 +1,76 @@
#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>
#include <limits.h>
int main(int argc, char** argv) {
if (argc != 2) {
fputs("Usage: ", stdout);
fputs(argv[0], stdout);
fputs(" <input file>\n", stdout);
return 1;
}
FILE* file = fopen(argv[1], "r");
unsigned int safe_count = 0;
const int max_length = 16;
char buffer[17];
int buf_length = 0;
int line_no = 0;
while (true) {
bool first_number = true;
int last_number = INT_MIN;
int last_delta = 0;
bool safe = true;
int c;
while (true) {
c = fgetc(file);
if (buf_length < max_length && c >= '0' && c <= '9') {
buffer[buf_length] = c;
buf_length++;
continue;
}
if (buf_length > 0) {
buffer[buf_length] = 0;
int number = atoi(buffer);
if (first_number) {
first_number = false;
} else {
int delta = number - last_number;
if (last_delta != 0 && delta * last_delta < 0) {
safe = false;
} else if (delta == 0 || abs(delta) > 3) {
safe = false;
}
last_delta = delta;
}
last_number = number;
buf_length = 0;
}
if (c == EOF || c == '\n') {
break;
}
}
if (safe && !first_number) {
safe_count++;
}
line_no++;
if (c == EOF) {
break;
}
}
printf("Safe count: %d\n", safe_count);
fclose(file);
}