advent2021

Advent of Code 2021 Solutions
git clone git://bsandro.tech/advent2021
Log | Files | Refs | README | LICENSE

puzzle2.c (1127B)


      1 #include <stdio.h>
      2 #include <stdlib.h>
      3 #include <errno.h>
      4 #include <string.h>
      5 #include <strings.h>
      6 #include <stdbool.h>
      7 
      8 #define MAX_LEN 8
      9 
     10 void rotate_window(int window[3]) {
     11 	int tmp = window[0];
     12 	window[0] = window[1];
     13 	window[1] = window[2];
     14 	window[2] = tmp;
     15 }
     16 
     17 int sum_window(int window[3]) {
     18 	return window[0] + window[1] + window[2];
     19 }
     20 
     21 int sum_new_window(int window[3], int value) {
     22 	return window[1] + window[2] + value;
     23 }
     24 
     25 bool is_window_full(int window[3]) {
     26 	return window[0] > 0 && window[1] > 0 && window[2] > 0;
     27 }
     28 
     29 int puzzle2(const char *filename) {
     30 	FILE *infile = fopen(filename, "r");
     31 	if (infile == NULL) {
     32 		fprintf(stderr, "fopen() error: %s\n", strerror(errno));
     33 		return -1;
     34 	}
     35 
     36 	char buf[MAX_LEN] = {0};
     37 	int window[3] = {0, 0, 0};
     38 	int counter = 0;
     39 
     40 	while (fgets(buf, MAX_LEN, infile) != NULL) {
     41 		int depth = atoi(buf);
     42 		int sum_win = sum_window(window);
     43 		int sum_new = sum_new_window(window, depth);
     44 		if (is_window_full(window) && sum_win > 0 && sum_new > sum_win) {
     45 			++counter;
     46 		}
     47 		rotate_window(window);
     48 		window[2] = depth;
     49 		bzero(buf, MAX_LEN);
     50 	}
     51 
     52 	fclose(infile);
     53 	return counter;
     54 }