summaryrefslogtreecommitdiffstats
path: root/2021/day1/depth.c
blob: eff19b4ea81078733da3bd331895830481d70917 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>

int main(int argc, char *argv[])
{
	if (argc != 2) {
		printf("Usage: ./depth <input-file>\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;
}