Advertisement
Guest User

Untitled

a guest
Dec 3rd, 2017
95
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.39 KB | None | 0 0
  1. #include "AdventOfCode2k17.h"
  2. #include <vector>
  3. #include <iterator>
  4. #include <numeric>
  5. #include <algorithm>
  6. #include <sstream>
  7. #include <string>
  8. #include <map>
  9. #include <complex>
  10.  
  11. struct dir {
  12.     int x, y, dx, dy;  
  13. };
  14.  
  15. const dir & next(const dir & inp) {
  16.     const bool rot = inp.x == inp.y || (inp.x < 0 && inp.x == -inp.y) || (inp.x > 0 && inp.x == 1 - inp.y);
  17.     const int dx = rot ? -inp.dy : inp.dx;
  18.     const int dy = rot ? inp.dx : inp.dy;
  19.     return dir{ inp.x + dx,inp.y + dy, dx, dy };
  20. }
  21.  
  22. template<>
  23. void solve<Day3>(std::istream & is, std::ostream & os, bool part2) {
  24.     int num = 0, dist; is >> num;
  25.     if (!part2) {
  26.         for (int i = 1; i < num; ++i) {
  27.             int side = (2 * i + 1);
  28.             int sq = side * side;
  29.             if (sq > num) {
  30.                 int corr = (2 * i - 1)*(2 * i - 1);
  31.                 dist = i + abs(((num - corr) % (2 * i)) - i);
  32.                 break;
  33.             }
  34.         }
  35.     }
  36.     else {
  37.         dir node{ 0,0,0,-1 };
  38.         std::map<std::pair<int,int>, int> spiral;
  39.         spiral[std::make_pair(node.x, node.y)] = 1;
  40.         int sum = 0;       
  41.         while (sum < num) {
  42.             node = next(node);
  43.             sum = 0;
  44.             for (int dx = -1; dx < 2; ++dx) {
  45.                 for (int dy = -1; dy < 2; ++dy) {
  46.                     auto idx = std::make_pair(node.x + dx, node.y + dy);
  47.                     if (spiral.count(idx)) {                       
  48.                         sum += spiral[idx];
  49.                     }
  50.                 }
  51.             }
  52.             spiral[std::make_pair(node.x, node.y)] = sum;
  53.         }
  54.         dist = sum;
  55.     }
  56.     os << "part" << (part2 ? "2" : "1") << " =" << dist << " ";
  57. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement