Advertisement
Guest User

Untitled

a guest
Dec 6th, 2019
115
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.10 KB | None | 0 0
  1. #include <iostream>
  2. #include <string>
  3. #include <fstream>
  4. #include <sstream>
  5. #include <unordered_map>
  6. #include <utility>
  7. #include <functional>
  8.  
  9. struct Location
  10. {
  11. int x;
  12. int y;
  13. bool operator<(const Location& rhs) const {
  14. return x<rhs.x || (!(rhs.x<x) && y<rhs.y);
  15. }
  16.  
  17. bool operator==(const Location& rhs) const {
  18. return x == rhs.x && y == rhs.y;
  19. }
  20. };
  21.  
  22.  
  23. namespace std {
  24. template<>
  25. struct hash<Location> {
  26. size_t operator()(Location const& loc) const{
  27. return loc.x << 31 | loc.y;
  28. }
  29. };
  30.  
  31. }
  32. /* wires can probably intersect themselves, but in the map then will be
  33. only the one with smallest amount of steps, aka the first found */
  34. using WireMap = std::unordered_map<Location, int>;
  35.  
  36. static std::unordered_map<char, Location> directions = {
  37. {'L', {-1, 0}},
  38. {'R', { 1, 0}},
  39. {'U', { 0, 1}},
  40. {'D', { 0,-1}} };
  41.  
  42. WireMap ProcessDirections(const std::string &path) {
  43. WireMap wireMap;
  44. std::istringstream in(path);
  45.  
  46. char direction, delimiter;
  47. int x = 0, y = 0, distance;
  48. int steps = 1;
  49. while(in >> direction >> distance >> delimiter) {
  50. for (int i = 0; i < distance; i++) {
  51. x += directions[direction].x;
  52. y += directions[direction].y;
  53. wireMap.insert({{x,y}, steps++});
  54. }
  55. }
  56. return wireMap;
  57. }
  58.  
  59.  
  60.  
  61. int main() {
  62. std::ifstream inputFile("input");
  63. std::string firstLine, secondLine;
  64.  
  65. inputFile >> firstLine >> secondLine;
  66.  
  67. WireMap firstMap = ProcessDirections(firstLine);
  68. WireMap secondMap = ProcessDirections(secondLine);
  69.  
  70. int closestIntersection = firstMap.size() + secondMap.size();
  71. int leastStepsIntersection = firstMap.size() + secondMap.size();
  72.  
  73. for (auto [position, steps] : firstMap){
  74. if(secondMap.count(position) != 0){
  75. closestIntersection = std::min(closestIntersection, abs(position.x) + abs(position.y));
  76. leastStepsIntersection = std::min(leastStepsIntersection, firstMap[position] + secondMap[position]);
  77. }
  78. }
  79.  
  80. std::cout << "1. closest intersection Manhattan distance: " << closestIntersection << "\n";
  81. std::cout << "2. least amount of steps to an intersection: " << leastStepsIntersection << "\n";
  82. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement