Advertisement
AndryS1

Ulam Spiral

Mar 10th, 2023
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.18 KB | None | 0 0
  1. #include <string>
  2. #include <iostream>
  3. #include <cassert>
  4. #include <iomanip>
  5. void print_mat(int** mat, size_t size)
  6. {
  7. for (size_t i = 0; i < size; i++)
  8. {
  9. for (size_t j = 0; j < size; j++)
  10. {
  11. std::cout.width(3);
  12. std::cout << mat[i][j] << ' ';
  13. }
  14. std::cout << "\n";
  15. }
  16. }
  17.  
  18. void fill_line(int** spiral, size_t posx, size_t posy, int len, bool byX, int& num, bool upright = false)
  19. {
  20. // limiting bound of array to [0; inf]
  21. print_mat(spiral, 7);
  22. std::cout << '\n';
  23. //assert(!upright || (posx >= len) || !byX);
  24. //assert(!upright || (posy >= len) || byX);
  25.  
  26. if (byX)
  27. {
  28. for (int i = 0; i < len; i++)
  29. {
  30. int offset = upright ? -i : i;
  31. spiral[posy][posx + offset] = num;
  32.  
  33. num++;
  34. }
  35.  
  36. }
  37. else
  38. {
  39.  
  40. for (int i = 0; i < len; i++)
  41. {
  42. int offset = upright ? -i : i;
  43. spiral[posy + offset][posx] = num;
  44. num++;
  45. }
  46. }
  47. }
  48. static int num = 2;
  49. void fill_ulam(int** spiral, size_t posx, size_t posy, size_t depth = 1)
  50. {
  51. // fill up
  52. fill_line(spiral, posx, posy, depth * 2, false, num, true);
  53. posy -= depth * 2 - 1;
  54. posx -= 1;
  55. // fill left
  56. fill_line(spiral, posx, posy, depth * 2, true, num, true);
  57. posx -= depth * 2 - 1;
  58. posy += 1;
  59. // fill down
  60. fill_line(spiral, posx, posy, depth * 2, false, num, false);
  61. posy += depth * 2 - 1;
  62. posx += 1;
  63. // fill right
  64. fill_line(spiral, posx, posy, depth * 2, true, num, false);
  65. posx += depth * 2;
  66. if (depth == 10) return; // recursive end (limit of size of our matrix)
  67. // recursive continue
  68. fill_ulam(spiral, posx, posy, depth + 1);
  69.  
  70. }
  71.  
  72. int main()
  73. {
  74. constexpr size_t size = 2*10 + 1;
  75. int** spiral = new int* [size];
  76. for (size_t i = 0; i < size; i++) {
  77. spiral[i] = new int[size] {};
  78.  
  79. }
  80. spiral[size / 2][size / 2] = 1;
  81. fill_ulam(spiral, size / 2 + 1, size / 2);
  82. print_mat(spiral, size);
  83.  
  84. for (size_t i = 0; i < size; i++) {
  85. delete[] spiral[i];
  86. }
  87. delete[] spiral;
  88.  
  89. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement