From c83970e459635609f7b4520f4f73db8f70c973f8 Mon Sep 17 00:00:00 2001 From: Yigit Sever Date: Wed, 1 Dec 2021 13:53:26 +0300 Subject: 2021, day1: done --- 2021/day1/depth.c | 73 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 73 insertions(+) create mode 100644 2021/day1/depth.c (limited to '2021/day1/depth.c') diff --git a/2021/day1/depth.c b/2021/day1/depth.c new file mode 100644 index 0000000..eff19b4 --- /dev/null +++ b/2021/day1/depth.c @@ -0,0 +1,73 @@ +#include +#include +#include +#include + +int main(int argc, char *argv[]) +{ + if (argc != 2) { + printf("Usage: ./depth \n"); + exit(EXIT_FAILURE); + } + + FILE *fp; + char *buffer; + ssize_t read; + size_t len = 0; + + fp = fopen(argv[1], "r"); + if (fp == NULL) { + perror("fopen"); + exit(EXIT_FAILURE); + } + + int inc = 0; + int curr = 0; + uint8_t idx = 0; + int side = 0; + int depth[3] = { 0, 0, 0 }; + + read = getline(&buffer, &len, fp); + if (read != -1) { + depth[0] = atoi(buffer); + } + + read = getline(&buffer, &len, fp); + if (read != -1) { + curr = atoi(buffer); + depth[0] += curr; + depth[1] = curr; + } + + read = getline(&buffer, &len, fp); + if (read != -1) { + curr = atoi(buffer); + depth[0] += curr; + depth[1] += curr; + depth[2] = curr; + } + + while ((read = getline(&buffer, &len, fp)) != -1) { + side = depth[idx]; + depth[idx] = 0; + idx = (idx + 1) % 3; + + curr = atoi(buffer); + depth[0] += curr; + depth[1] += curr; + depth[2] += curr; + + if (depth[idx] > side) { + inc++; + } + } + + fclose(fp); + if (buffer) { + free(buffer); + } + + printf("%d", inc); + + return 0; +} -- cgit v1.2.3-70-g09d2