advent-of-code-2021/1/1-2.c

65 lines
1.7 KiB
C
Raw Normal View History

2021-12-01 23:53:22 +08:00
#include <stdlib.h>
#include <stdio.h>
#include <limits.h>
#include <stdbool.h>
#define N_WINDOWS 4
#define WINDOW_LENGTH 3
typedef struct
{
2021-12-04 21:30:27 +08:00
unsigned int sum;
unsigned int count;
2021-12-01 23:53:22 +08:00
bool written; // IGNORE COMPARISONS AT THE START.
} MEASUREMENT_WINDOW;
int main(int argc, char const *argv[])
{
FILE *p_file = fopen("input", "r");
char line[50];
2021-12-04 21:30:27 +08:00
unsigned int increases = 0;
2021-12-01 23:53:22 +08:00
MEASUREMENT_WINDOW windows[N_WINDOWS];
2021-12-04 21:30:27 +08:00
unsigned int i = 0;
2021-12-01 23:53:22 +08:00
while (fgets(line, sizeof line, p_file) != NULL)
{
2021-12-04 21:30:27 +08:00
unsigned int n = atoi(line);
2021-12-01 23:53:22 +08:00
// UPDATE MEASURING WINDOWS
for (size_t j = 0; j < N_WINDOWS; j++)
{
MEASUREMENT_WINDOW *window = &windows[j];
if ((i - j) % N_WINDOWS == 0)
{
window->count = 0;
window->sum = 0;
window->written = true;
}
if (window->written && window->count < 3)
{
window->sum += n;
window->count++;
}
}
// COMPARE WINDOWS
for (size_t j = 0; j < N_WINDOWS; j++)
{
MEASUREMENT_WINDOW *window = &windows[j];
// ONE WINDOW IS READY TO BE COMPARED
if (window->count == 3)
{
window->count++; // PREVENT DOUBLE-COMPARE OF WINDOW.
MEASUREMENT_WINDOW last_window = windows[(j + N_WINDOWS - 1) % 4];
if (last_window.written && window->written && window->sum > last_window.sum)
{
increases++;
}
continue;
}
}
i++;
}
printf("%u\n", increases);
return 0;
}