Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- struct point {
- int x;
- int y;
- };
- // this is arbitrary. just to make ordered containers work.
- bool operator<(const point & lhs, const point & rhs) {
- if(lhs.x != rhs.x) return lhs.x < rhs.x;
- return lhs.y < rhs.y;
- }
- typedef map<point, int> memory_map;
- point rotate(const point & p) {
- return point{-p.y, p.x };
- }
- int memory_value_for_point(const memory_map &memory, const point &p) {
- if(memory.find(p) == memory.end()) {
- return 0;
- }
- return memory.at(p);
- }
- int solve(int num) {
- point direction {1,0};
- point location {0,0};
- bool expand = false;
- int target_distance = 1;
- int current_distance = 0;
- memory_map spiral_memory;
- spiral_memory[location] = 1;
- while(spiral_memory[location] <= num) {
- location.x += direction.x;
- location.y += direction.y;
- spiral_memory[location] = memory_value_for_point(spiral_memory, {location.x + 1, location.y + 1})
- + memory_value_for_point(spiral_memory, {location.x, location.y + 1})
- + memory_value_for_point(spiral_memory, {location.x - 1, location.y + 1})
- + memory_value_for_point(spiral_memory, {location.x + 1, location.y})
- + memory_value_for_point(spiral_memory, {location.x - 1, location.y})
- + memory_value_for_point(spiral_memory, {location.x + 1, location.y - 1})
- + memory_value_for_point(spiral_memory, {location.x, location.y - 1})
- + memory_value_for_point(spiral_memory, {location.x - 1, location.y - 1});
- current_distance++;
- //cerr << "spiral_memory[(" << location.x << "," << location.y << ")] = " << memory_value_for_point(spiral_memory, location) << endl;
- if(current_distance == target_distance) {
- current_distance = 0;
- direction = rotate(direction);
- if(expand) {
- target_distance++;
- expand = false;
- } else {
- expand = true;
- }
- }
- }
- return spiral_memory[location];
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement