blob: 6c212b1759bb272582e8592bb55e4d75aae56277 (
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
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
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int pos = 0;
int depth = 0;
int aim = 0;
void ParseInput(char *filepath)
{
char ch;
FILE *fp;
fp = fopen(filepath, "r");
if (fp == NULL)
{
perror("Error while opening the file.\n");
exit(EXIT_FAILURE);
}
char command;
char char_x_val;
int current_type = 0; // 0 - command; 1 - skip; 2 - val
/* Part 1
while((ch= fgetc(fp)) != EOF)
{
if(ch == ' ')
{
current_type = 2;
}
else if(ch == '\n')
{
int x = atoi(&char_x_val);
switch(command)
{
case 'f':
pos += x;
break;
case 'd':
depth += x;
break;
case 'u':
depth -= x;
}
current_type = 0;
}
else if(current_type == 0)
{
command = ch;
current_type = 1;
}
else if(current_type == 2)
{
char_x_val = ch;
}
}
*/
/* Part2 */
while((ch= fgetc(fp)) != EOF)
{
if(ch == ' ')
{
current_type = 2;
}
else if(ch == '\n')
{
int x = atoi(&char_x_val);
switch(command)
{
case 'f':
pos += x;
depth += aim * x;
break;
case 'd':
aim += x;
break;
case 'u':
aim -= x;
}
current_type = 0;
}
else if(current_type == 0)
{
command = ch;
current_type = 1;
}
else if(current_type == 2)
{
char_x_val = ch;
}
}
fclose(fp);
}
int main(void)
{
ParseInput("input-2.txt");
printf("pos: %d, depth: %d; product: %d", pos, depth, pos * depth);
return 0;
}
|