-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpuzzle1.cpp
More file actions
129 lines (108 loc) · 1.66 KB
/
puzzle1.cpp
File metadata and controls
129 lines (108 loc) · 1.66 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
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <vector>
using namespace std;
struct Move {
int rot;
int length;
};
void print_moves(vector<Move>& moves)
{
printf("Moves:\n");
for(std::vector<Move>::iterator it = moves.begin();
it != moves.end();
++it)
{
if (it->rot == 1)
{
printf("R");
}
else
{
printf("L");
}
printf("%i ", it->length);
}
printf("\n");
}
vector<Move> read_moves(const char* pFilename)
{
FILE* pFile = fopen(pFilename, "rb");
if (pFile == NULL)
{
printf("Failed to open %s\n", pFilename);
exit(1);
}
int c;
vector<Move> moves;
Move m;
m.length = 0;
while(true)
{
c = fgetc(pFile);
if (feof(pFile))
{
break;
}
if (c=='R')
{
m.rot = 1;
}
else if (c=='L')
{
m.rot = -1;
}
else if (strchr("0123456789", c) != NULL)
{
m.length = (m.length * 10) + (c - (int)'0');
}
else if (c==',')
{
moves.push_back(m);
m.length = 0;
}
}
moves.push_back(m);
return moves;
}
struct State {
int x, y, rot;
};
struct Position {
int x, y;
};
Position dir[] = {
{ 0, 1 },
{ 1, 0 },
{ 0, -1 },
{ -1, 0 },
};
void play_moves(vector<Move>& moves, State& s)
{
for(std::vector<Move>::iterator it = moves.begin();
it != moves.end();
++it)
{
s.rot = (s.rot + it->rot + 4) % 4;
s.x += dir[s.rot].x * it->length;
s.y += dir[s.rot].y * it->length;
}
}
void print_state(State& s)
{
printf("State x %i, y %i rot %i\n", s.x, s.y, s.rot);
}
int main()
{
vector<Move> moves = read_moves("day1input.txt");
print_moves(moves);
State s;
s.x = 0;
s.y = 0;
s.rot = 0;
play_moves(moves, s);
print_state(s);
printf("Answer : %i\n", s.x + s.y);
return 0;
}