-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDay02.c
More file actions
108 lines (85 loc) · 2.39 KB
/
Day02.c
File metadata and controls
108 lines (85 loc) · 2.39 KB
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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
#include "Helpers.c"
#define CAP 4096
typedef enum {
Idle = 0,
Forward,
Down,
Up
} Direction;
typedef struct {
Direction dir;
int delta;
} Command;
static int parse(const char *input, Command commands[CAP]) {
char dirString[32] = {0};
int charsRead = 0;
int filled = 0;
int n = 0;
while ((filled = sscanf(input, "%31s %u\n%n", dirString, &commands[n].delta, &charsRead)) != EOF) {
assert(filled == 2 && "parseInput: Failed to parse input");
Direction dir =
strcmp(dirString, "forward") == 0 ? Forward
: strcmp(dirString, "down") == 0 ? Down
: strcmp(dirString, "up") == 0 ? Up
: Idle;
assert(dir != Idle && "parseInput: Unknown direction");
commands[n++].dir = dir;
assert(n < CAP);
input += charsRead;
}
return n;
}
static int partOne(int n, const Command commands[n]) {
int horizontalPos = 0;
int depth = 0;
for (const Command *command = commands; command < commands + n; ++command) {
switch (command->dir) {
case Up:
depth -= command->delta;
break;
case Down:
depth += command->delta;
break;
case Forward:
horizontalPos += command->delta;
break;
case Idle:
break;
}
}
return horizontalPos * depth;
}
static int partTwo(int n, const Command commands[n]) {
int horizontalPos = 0;
int depth = 0;
int aim = 0;
for (const Command *command = commands; command < commands + n; ++command) {
switch (command->dir) {
case Up:
aim -= command->delta;
break;
case Down:
aim += command->delta;
break;
case Forward:
horizontalPos += command->delta;
depth += aim * command->delta;
break;
case Idle:
break;
}
}
return horizontalPos * depth;
}
int main() {
const char *input = Helpers_readInputFile(__FILE__);
Command commands[CAP] = {0};
int n = parse(input, commands);
Helpers_assert(PART1, Helpers_clock(),
partOne(n, commands),
150, 1815044);
Helpers_assert(PART2, Helpers_clock(),
partTwo(n, commands),
900, 1739283308);
return 0;
}