This repository has been archived by the owner on Jun 10, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
day13_p1.cpp
56 lines (49 loc) · 2.15 KB
/
day13_p1.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
#include <fstream>
#include <iostream>
int compare_packets(std::pair<std::string,std::string> packet){
std::pair<std::string::iterator,std::string::iterator> it;
std::pair<std::string,std::string> subpacket;
packet.first = packet.first.substr(1,packet.first.size()-2);
packet.second = packet.second.substr(1,packet.second.size()-2);
for(it.first = packet.first.begin(), it.second = packet.second.begin(); it.first < packet.first.end() && it.second < packet.second.end(); it.first++, it.second++){
if(*it.first != '[' && *it.second != '[' && *it.first != *it.second) return ((*it.first < *it.second) ? +1 : -1);
if(*it.first == '[' || *it.second == '['){
if(*it.first == '['){
int cnt = 1, size1 = 0;
while(cnt > 0){
if(*(it.first+(++size1)) == '[') cnt++;
if(*(it.first+size1) == ']') cnt--;
}
subpacket.first = packet.first.substr(it.first-packet.first.begin(),size1+1);
it.first += size1;
}
else subpacket.first = std::string("[") + *it.first + std::string("]");
if(*it.second == '['){
int cnt = 1, size2 = 0;
while(cnt > 0){
if(*(it.second+(++size2)) == '[') cnt++;
if(*(it.second+size2) == ']') cnt--;
}
subpacket.second = packet.second.substr(it.second-packet.second.begin(),size2+1);
it.second += size2;
}
else subpacket.second = std::string("[") + *it.second + std::string("]");
int ret = compare_packets(subpacket); if(ret) return ret;
}
}
return ((+1)*(it.first == packet.first.end()) + (-1)*(it.second == packet.second.end()));
}
int main(int argc, char const *argv[]) {
std::ifstream file("input13.txt");
std::pair<std::string,std::string> line; size_t i;
unsigned int solution = 0;
for(unsigned int k = 1; !file.eof(); k++){
file >> line.first >> line.second;
while((i = line.first.find("10")) != std::string::npos) line.first.replace(i,2,":");
while((i = line.second.find("10")) != std::string::npos) line.second.replace(i,2,":");
solution += k*(compare_packets(line) > 0);
file.ignore(2);
}
std::cout << "Solution = " << solution << std::endl;
return 0;
}