aboutsummaryrefslogtreecommitdiff
path: root/2020/12/puzzle-1.c
blob: 1a4c7abdc74674def3812f7b64a96b7f802e606f (plain) (blame)
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 <err.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int
main(void)
{
	FILE *fp;
	char cl[5];
	int north, east;
	int direction = 0;

	if (!(fp = fopen("input", "r")))
		err(EXIT_FAILURE, "fopen");

	north = east = 0;
	while (fgets(cl, sizeof(cl), fp) != NULL) {
		switch (cl[0]) {
		case 'N':
			north += atoi(&cl[1]);
			break;
		case 'E':
			east += atoi(&cl[1]);
			break;
		case 'S':
			north -= atoi(&cl[1]);
			break;
		case 'W':
			east -= atoi(&cl[1]);
			break;
		case 'L':
			direction -= atoi(&cl[1]);
			goto wrap;
		case 'R':
			direction += atoi(&cl[1]);

wrap:
			/* 0 <= direction < 360 */
			if (direction >= 360)
				direction -= 360;
			else if (direction < 0)
				direction += 360;
			break;
		case 'F':
			switch (direction) {
			case 0:
				east += atoi(&cl[1]);
				break;
			case 90:
				north -= atoi(&cl[1]);
				break;
			case 180:
				east -= atoi(&cl[1]);
				break;
			case 270:
				north += atoi(&cl[1]);
				break;
			}
			break;
		}
	}
	fclose(fp);

	/* Absolute value */
	if (north < 0)
		north = -north;
	if (east < 0)
		east = -east;

	printf("%d\n", north + east);
	return EXIT_SUCCESS;
}