diff --git a/02/src/main.c b/02/src/main.c index 70ba1e7..59e6ba1 100644 --- a/02/src/main.c +++ b/02/src/main.c @@ -1,12 +1,23 @@ /** - * Copyright [2023] Jiří Štefka + * Copyright [2024] Jiří Štefka * Project: AdventOfCode * @file main.c * @brief Main entry point * @author jiriks74 */ +#define _GNU_SOURCE + +#include #include +#include +#include + +enum STATUS { + DECREASING, + INIT, + INCREASING, +}; /** * @brief Main entry point @@ -20,6 +31,81 @@ int main(int argc, char *argv[]) int main_test(int argc, char *argv[]) #endif { - printf("Hello world!\n"); + FILE *file; + if (argc > 1) + file = fopen(argv[1], "r"); + else { + fprintf(stderr, "No file was given.\n"); + return 1; + } +if (file == NULL) { + fprintf(stderr, "Couldn't open file '%s'\n", argv[1]); + return 1; + } + + char *buffer = NULL; + size_t bufferSize = 0; + int status = INIT; + uint safeCount = 0; + while (getline(&buffer, &bufferSize, file) != -1) { + char *token = strtok(buffer, " "); + int previousLevel = 0; + + if (sscanf(token, "%d", &previousLevel) == EOF) { + fprintf(stderr, "Error: Wrong input file format!"); + return 1; + } + + token = strtok(NULL, " "); + int currentLevel = 0; + if (sscanf(token, "%d", ¤tLevel) == EOF) { + fprintf(stderr, "Error: Wrong input file format!"); + return 1; + } + if (currentLevel > previousLevel) + status = INCREASING; + else + status = DECREASING; + + if (status == INCREASING) { + if (currentLevel - previousLevel < 1 | currentLevel - previousLevel > 3) + continue; + } else { + if (previousLevel - currentLevel < 1 | previousLevel - currentLevel > 3) + continue; + } + + token = strtok(NULL, " "); + + bool finished = true; + while (token != NULL) { + previousLevel = currentLevel; + if (sscanf(token, "%d", ¤tLevel) == EOF) { + fprintf(stderr, "Error: Wrong input file format!"); + return 1; + } + if (status == INCREASING) { + if (currentLevel - previousLevel < 1 | + currentLevel - previousLevel > 3) { + finished = false; + break; + } + } else { + if (previousLevel - currentLevel < 1 | + previousLevel - currentLevel > 3) { + finished = false; + break; + } + } + token = strtok(NULL, " "); + } + if (finished) + safeCount++; + } + free(buffer); + fclose(file); + + printf("Safe count: %d\n", safeCount); + return 0; }