Advertisement
Guest User

aoc2017-day3part2

a guest
Dec 3rd, 2017
102
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.36 KB | None | 0 0
  1.     struct point {
  2.         int x;
  3.         int y;
  4.     };
  5.  
  6.     // this is arbitrary. just to make ordered containers work.
  7.     bool operator<(const point & lhs, const point & rhs) {
  8.         if(lhs.x != rhs.x) return lhs.x < rhs.x;
  9.         return lhs.y < rhs.y;
  10.     }
  11.  
  12.     typedef map<point, int> memory_map;
  13.  
  14.     point rotate(const point & p) {
  15.         return point{-p.y, p.x };
  16.     }
  17.  
  18.  
  19.     int memory_value_for_point(const memory_map &memory, const point &p) {
  20.         if(memory.find(p) == memory.end()) {
  21.             return 0;
  22.         }
  23.         return memory.at(p);
  24.     }
  25.  
  26.  
  27.     int solve(int num) {
  28.         point direction {1,0};
  29.         point location {0,0};
  30.         bool expand = false;
  31.         int target_distance = 1;
  32.         int current_distance = 0;
  33.         memory_map spiral_memory;
  34.         spiral_memory[location] = 1;
  35.         while(spiral_memory[location] <= num) {
  36.             location.x += direction.x;
  37.             location.y += direction.y;
  38.             spiral_memory[location] = memory_value_for_point(spiral_memory, {location.x + 1, location.y + 1})
  39.                                 + memory_value_for_point(spiral_memory, {location.x, location.y + 1})
  40.                                 + memory_value_for_point(spiral_memory, {location.x - 1, location.y + 1})
  41.                                 + memory_value_for_point(spiral_memory, {location.x + 1, location.y})
  42.                                 + memory_value_for_point(spiral_memory, {location.x - 1, location.y})
  43.                                 + memory_value_for_point(spiral_memory, {location.x + 1, location.y - 1})
  44.                                 + memory_value_for_point(spiral_memory, {location.x, location.y - 1})
  45.                                 + memory_value_for_point(spiral_memory, {location.x - 1, location.y - 1});
  46.             current_distance++;
  47.             //cerr << "spiral_memory[(" << location.x << "," << location.y << ")] = " << memory_value_for_point(spiral_memory, location) << endl;
  48.             if(current_distance == target_distance) {
  49.                 current_distance = 0;
  50.                 direction = rotate(direction);
  51.                 if(expand) {
  52.                     target_distance++;
  53.                     expand = false;
  54.                 } else {
  55.                     expand = true;
  56.                 }
  57.             }
  58.  
  59.         }
  60.         return spiral_memory[location];
  61.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement