summaryrefslogtreecommitdiffstats
path: root/2021/day2/pilot.c
blob: 6bc063086b571965186e67e16127587aba8538c7 (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
#include <stdio.h>
#include <stdlib.h>
#include <string.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 scalar;
	char *way;
	int h_pos = 0, depth = 0, aim = 0;
	while ((read = getline(&buffer, &len, fp)) != -1) {
		sscanf(buffer, "%s %d", way, &scalar);
		// printf("READ: <%s>, <%d>\n", way, scalar);

		if (strncmp(way, "forward", strlen("forward")) == 0) {
			// printf("GOING FORWARD\n");
			h_pos += scalar;
			depth += aim * scalar;
		} else if (strncmp(way, "down", strlen("forward")) == 0) {
			aim += scalar;
		} else { /* up */
			aim -= scalar;
		}
	}

	printf("%d\n", depth * h_pos);

	return 0;
}