Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <string>
- #include <fstream>
- #include <sstream>
- #include <unordered_map>
- #include <utility>
- #include <functional>
- struct Location
- {
- int x;
- int y;
- bool operator<(const Location& rhs) const {
- return x<rhs.x || (!(rhs.x<x) && y<rhs.y);
- }
- bool operator==(const Location& rhs) const {
- return x == rhs.x && y == rhs.y;
- }
- };
- namespace std {
- template<>
- struct hash<Location> {
- size_t operator()(Location const& loc) const{
- return loc.x << 31 | loc.y;
- }
- };
- }
- /* wires can probably intersect themselves, but in the map then will be
- only the one with smallest amount of steps, aka the first found */
- using WireMap = std::unordered_map<Location, int>;
- static std::unordered_map<char, Location> directions = {
- {'L', {-1, 0}},
- {'R', { 1, 0}},
- {'U', { 0, 1}},
- {'D', { 0,-1}} };
- WireMap ProcessDirections(const std::string &path) {
- WireMap wireMap;
- std::istringstream in(path);
- char direction, delimiter;
- int x = 0, y = 0, distance;
- int steps = 1;
- while(in >> direction >> distance >> delimiter) {
- for (int i = 0; i < distance; i++) {
- x += directions[direction].x;
- y += directions[direction].y;
- wireMap.insert({{x,y}, steps++});
- }
- }
- return wireMap;
- }
- int main() {
- std::ifstream inputFile("input");
- std::string firstLine, secondLine;
- inputFile >> firstLine >> secondLine;
- WireMap firstMap = ProcessDirections(firstLine);
- WireMap secondMap = ProcessDirections(secondLine);
- int closestIntersection = firstMap.size() + secondMap.size();
- int leastStepsIntersection = firstMap.size() + secondMap.size();
- for (auto [position, steps] : firstMap){
- if(secondMap.count(position) != 0){
- closestIntersection = std::min(closestIntersection, abs(position.x) + abs(position.y));
- leastStepsIntersection = std::min(leastStepsIntersection, firstMap[position] + secondMap[position]);
- }
- }
- std::cout << "1. closest intersection Manhattan distance: " << closestIntersection << "\n";
- std::cout << "2. least amount of steps to an intersection: " << leastStepsIntersection << "\n";
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement