feat(02): Solve day 2, part 1
This commit is contained in:
parent
76d836691b
commit
a83a7f3a34
@ -1,12 +1,23 @@
|
||||
/**
|
||||
* Copyright [2023] Jiří Štefka <jiriks74>
|
||||
* Copyright [2024] Jiří Štefka <jiriks74>
|
||||
* Project: AdventOfCode
|
||||
* @file main.c
|
||||
* @brief Main entry point
|
||||
* @author jiriks74
|
||||
*/
|
||||
|
||||
#define _GNU_SOURCE
|
||||
|
||||
#include <stdbool.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
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;
|
||||
}
|
||||
|
Loading…
x
Reference in New Issue
Block a user