#include #include #include #include #include #include #include #include std::vector split(const std::string &s, const char &delimiter) { std::vector tokens; std::string token; std::istringstream token_stream(s); while(std::getline(token_stream, token, delimiter)) tokens.push_back(token); return tokens; } std::vector> read_input_file() { std::ifstream file("input"); std::vector> data; std::string line; while(std::getline(file, line)) data.push_back(split(line, ',')); return data; } std::vector> write_path(const std::vector &directions) { std::pair position(0, 0); std::vector> path; for(const std::string &direction: directions) { char heading = direction[0]; int amount = stoi(direction.substr(1)); if(heading == 'R') { for(int i = position.first; i < position.first + amount; i++) path.push_back({i, position.second}); position = {position.first + amount, position.second}; }else if(heading == 'L') { for(int i = position.first; i > position.first - amount; i--) path.push_back({i, position.second}); position = {position.first - amount, position.second}; }else if(heading == 'U') { for(int i = position.second; i > position.second - amount; i--) path.push_back({position.first, i}); position = {position.first, position.second - amount}; }else if(heading == 'D') { for(int i = position.second; i < position.second + amount; i++) path.push_back({position.first, i}); position = {position.first, position.second + amount}; } } return path; } std::vector> find_intersections(std::vector> path_a, std::vector> path_b) { std::vector> intersections; for(auto &p1: path_a) { for(auto &p2: path_b) { if(p1 == p2) intersections.push_back(p1); } } return intersections;; } int min_distance(std::vector> points) { int min = 999; for(auto &point: points) { if(point == std::make_pair(0, 0)) continue; int distance = std::abs(0 - point.first) + std::abs(0 - point.second); if(distance < min) min = distance; } return min; } int min_path(std::vector> path_a, std::vector> path_b, std::vector> points) { int min = 999999; for(auto &point: points) { if(point == std::make_pair(0, 0)) continue; int distance_a = 0; int distance_b = 0; for(auto &p: path_a) { if(p == point) break; distance_a++; } for(auto &p: path_b) { if(p == point) break; distance_b++; } if ((distance_a + distance_b) < min) min = distance_a + distance_b; } return min; } int main() { auto data = read_input_file(); std::vector>> paths; for(auto &line: data) { auto path = write_path(line); paths.push_back(path); } auto intersections = find_intersections(paths[0], paths[1]); std::cout << min_distance(intersections) << std::endl; std::cout << min_path(paths[0], paths[1], intersections) << std::endl; return 0; }