-
Notifications
You must be signed in to change notification settings - Fork 9
/
day_13a.cpp
95 lines (87 loc) · 2.41 KB
/
day_13a.cpp
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
#include <fstream>
#include <iostream>
#include <string>
bool is_number (const char c) {
return c >= '0' && c <= '9';
}
void debug_print(const std::string& packet1, const std::string& packet2, const int i1, const int i2) {
std::cout << packet1 << ' ' << packet2 << '\n';
for (int i = 0; i < i1; i++) std::cout << ' ';
std::cout << '^';
for (int i = i1 + 1; i < packet1.size(); i++) std::cout << ' ';
std::cout << ' ';
for (int i = 0; i < i2; i++) std::cout << ' ';
std::cout << '^';
for (int i = i2 + 1; i < packet2.size(); i++) std::cout << ' ';
std::cout << '\n';
}
bool compare (const std::string& packet1, const std::string& packet2) {
int i1 = 0;
int i2 = 0;
while (i1 < packet1.size() && i2 < packet2.size()) {
if (is_number(packet1[i1]) && is_number(packet2[i2])) {
int n1 = 0;
while (is_number(packet1[i1])) {
n1 = n1 * 10 + (packet1[i1] - '0');
i1++;
}
int n2 = 0;
while (is_number(packet2[i2])) {
n2 = n2 * 10 + (packet2[i2] - '0');
i2++;
}
if (n1 == n2) {
// debug_print(packet1, packet2, i1, i2);
// std::cout << "Equal" << '\n';
continue;
}
if (n1 < n2) {
// debug_print(packet1, packet2, i1, i2);
// std::cout << "Correct order" << '\n';
return true;
}
break;
} else if (packet1[i1] == packet2[i2]) {
i1++;
i2++;
} else if (packet1[i1] == ']') {
// debug_print(packet1, packet2, i1, i2);
// std::cout << "Correct order" << '\n';
return true;
} else if (packet2[i2] == ']') {
break;
} else if (packet1[i1] == '[' || packet1[i1] == ',') {
i1++;
} else if (packet2[i2] == ',' || packet2[i2] == '[') {
i2++;
}
}
if (i1 == packet1.size()) {
// debug_print(packet1, packet2, i1, i2);
// std::cout << "Correct order" << '\n';
return true;
}
// debug_print(packet1, packet2, i1, i2);
// std::cout << "Wrong order" << '\n';
return false;
}
int main(int argc, char * argv[]) {
std::string input = "../input/day_13_input";
if (argc > 1) {
input = argv[1];
}
std::string packet1, packet2;
std::fstream file(input);
int index = 0;
int sum = 0;
while(std::getline(file, packet1)) {
if (packet1.empty()) continue;
std::getline(file, packet2);
index++;
if (compare(packet1, packet2)) {
sum += index;
}
}
std::cout << sum << '\n';
return 0;
}