Guest User

Spiral numbers

a guest
Dec 13th, 2014
13
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.57 KB | None | 0 0
  1. #include <iostream>
  2. #include <iomanip>
  3. #include <algorithm>
  4.  
  5. using namespace std;
  6.  
  7. int x_ge_y(const int x, const int y)
  8. {
  9.         return abs(abs(x - y) - 1 - abs(y - x - 1)) / 2;
  10. }
  11.  
  12. int x_lt_y(const int x, const int y)
  13. {
  14.         return 1 - x_ge_y(x, y);
  15. }
  16.  
  17. int get_value(const int size, const int x, const int y)
  18. {
  19.         const int x_centric = x - (size - 1) / 2;
  20.         const int y_centric = y - (size - 1) / 2;
  21.  
  22.         const int current_subsquare_half = max(abs(x_centric), abs(y_centric));
  23.         const int current_subsquare = current_subsquare_half * 2 + 1;
  24.  
  25.         const int x_local = x_centric + current_subsquare_half;
  26.         const int y_local = y_centric + current_subsquare_half;
  27.  
  28.         const int top_right_value = x_ge_y(x_local, y_local) * (x_local + y_local);
  29.         const int bottom_left_value = x_lt_y(x_local, y_local) * (2 * (current_subsquare - 1) + ((current_subsquare - 1) - x_local) + ((current_subsquare - 1) - y_local));
  30.  
  31.         const int inverted_value_local = top_right_value + bottom_left_value;
  32.         const int inverted_value = current_subsquare * current_subsquare - 1 - inverted_value_local;
  33.  
  34.         return size * size - inverted_value;
  35. }
  36.  
  37. int main()
  38. {
  39.         cout << "------" << endl;
  40.  
  41.         const int size = 9;
  42.  
  43.         for (int i = 0; i < size; ++i)
  44.         {
  45.                 for (int j = 0; j < size; ++j)
  46.                 {
  47.                         cout << setw(3) << get_value(size, j, i);
  48.                 };
  49.                 cout << endl;
  50.         };
  51.  
  52.         cout << "------" << endl;
  53.         return 0;
  54. }
Advertisement
Add Comment
Please, Sign In to add comment