kalin729

coordinates of outward spiral

Mar 7th, 2021 (edited)
249
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.17 KB | None | 0 0
  1. #include<iostream>
  2. using namespace std;
  3.  
  4. void spiral(int n){
  5.     int last_x, last_y;
  6.         // (dx, dy) is a vector - direction in which we move right now
  7.     int dx = 1;
  8.     int dy = 0;
  9.     // length of current segment
  10.     int segment_length = 1;
  11.  
  12.     // current position (x, y) and how much of current segment we passed
  13.     int x = 0;
  14.     int y = 0;
  15.     int segment_passed = 0;
  16.     for (int k = 0; k < n; ++k) {
  17.         // make a step, add 'direction' vector (dx, dy) to current position (x, y)
  18.         x += dx;
  19.         y += dy;
  20.         ++segment_passed;
  21.  
  22.         //save last result of x and y to print
  23.         last_x = x;
  24.         last_y = y;
  25.  
  26.         if (segment_passed == segment_length) {
  27.             // done with current segment
  28.             segment_passed = 0;
  29.  
  30.             // 'rotate' directions
  31.             int buffer = dx;
  32.             dx = -dy;
  33.             dy = buffer;
  34.  
  35.             // increase segment length if necessary
  36.             if (dy == 0) {
  37.                 ++segment_length;
  38.             }
  39.         }
  40.     }
  41.  
  42.     cout << last_x << " " << last_y << endl;
  43. }
  44.  
  45. int main(){
  46.  
  47.     int n;
  48.     cin >> n;
  49.     spiral(n);
  50.  
  51.     return 0;
  52. }
  53.  
Add Comment
Please, Sign In to add comment