~jbauer/advent-of-code

ref: 9149ffedaf4231a9431cf7102332093c3c5dfb04 advent-of-code/main1.c -rw-r--r-- 855 bytes
9149ffedJake Bauer Complete Day 2 challenges 7 months ago
                                                                                
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
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

FILE *
openInputFile(void)
{
	FILE *fp = fopen("input.txt","r");
	if (fp == NULL)
	{
		printf("Could not open file: input.txt\n");
		exit(EXIT_FAILURE);
	}
	return fp;
}

int
main(void)
{
	FILE *fp = openInputFile();

	int position = 0;
	int depth = 0;

	char *line = NULL;
	size_t len = 0;
	ssize_t read;
	while ((read = getline(&line, &len, fp)) != -1)
	{
		char *direction = strtok(line, " ");
		int magnitude = atoi(strtok(NULL, " "));

		if (strcmp("forward", direction) == 0)
			position += magnitude;
		else if (strcmp ("down", direction) == 0)
			depth += magnitude;
		else
			depth -= magnitude;
	}

	printf("Final position: %d\n", position);
	printf("Final depth: %d\n", depth);
	printf("Product: %d\n", position * depth);

	fclose(fp);
	if (line)
		free(line);
	exit(EXIT_SUCCESS);
}