下面的程序列出了螺旋的 (x, y) 序列。第一个列表使用位于 (0, 0) 的起点。第二个将螺旋的起点移动到 (minimum.x, minimum.y) 的位置。最小值保持左下元素的坐标。
你可以在程序中观察螺旋规则。位置 (x,y) 首先从 (n, n-1) 开始,其中 n 是螺旋的第 n 个循环。首先,向下移动位置,--y,直到y到达-n;然后将 x 向左移动,直到 x = -n;然后向上移动 y 直到 y=n;最后,向右移动 x 直到 x = n。在下面的程序 max(n) set = 4 中,有 4 个螺旋循环。您可以调整此参数 n 以适合您的目的。
每个螺旋循环的总数=8*n,除了最里面的循环(0,0),个数=1。因此,螺旋的元素个数=1 + 8*1 + 8*2 + 8*3 +.... 你必须首先通过输入字符串 L 的长度来确定螺旋的循环,循环数等于 `n = ( (L-1) / 8 + 1 );` 或 `n = ( (L-1) / 8 );` 如果没有剩余。
#include <iostream>
#include <vector>
struct int2 {
int x, y;
int2():x(0), y(0) {}
int2(const int a, const int b):x(a), y(b) {}
int2& operator=(const int2&) = default;
void print() const {std::cout << "( " << x <<", " << y << ") "; }
int2& operator+=(const int2&a) { this->x += a.x ; this->y += a.y; return *this;}
int2& operator-() {x = -x; y = -y; return *this;}
};
int main()
{
std::vector<int2> spiral;
int2 pos, minimum;
int n;
pos = int2(0,0);
minimum = pos;
spiral.push_back(pos);
for (n=1; n<5; n++)
{
pos = int2( n, n-1); // starting point for ith loop
spiral.push_back(pos);
while (pos.y > -n) {--pos.y; spiral.push_back(pos); if (pos.y < minimum.y) minimum.y = pos.y;}
while (pos.x > -n) {--pos.x; spiral.push_back(pos); if (pos.x < minimum.x) minimum.x = pos.x; }
while (pos.y < n) {++pos.y; spiral.push_back(pos); }
while (pos.x < n) {++pos.x; spiral.push_back(pos); }
}
-minimum;
std::cout << "center at (0, 0)\n";
for (int i=0; i<spiral.size(); i++) spiral[i].print();
std::cout<<std::endl;
for (int i=0; i<spiral.size(); i++) spiral[i] += minimum;
std::cout << "center at "; minimum.print(); std::cout<<std::endl;
for (int i=0; i<spiral.size(); i++) spiral[i].print();
std::cout<<std::endl;
return 0;
}
上面的 (x, y) 位置为您提供了二维序列数组 [x][y] 来编写您形成螺旋结构的 char。
center at (0, 0)
( 0, 0) ( 1, 0) ( 1, -1) ( 0, -1) ( -1, -1) ( -1, 0) ( -1, 1) ( 0, 1) ( 1, 1) ( 2, 1) ( 2, 0) ( 2, -1) ( 2, -2) ( 1, -2) ( 0, -2) ( -1, -2) ( -2, -2) ( -2, -1) ( -2, 0) ( -2, 1) ( -2, 2) ( -1, 2) ( 0, 2) ( 1, 2) ( 2, 2) ( 3, 2) ( 3, 1) ( 3, 0) ( 3, -1) ( 3, -2) ( 3, -3) ( 2, -3) ( 1, -3) ( 0, -3) ( -1, -3) ( -2, -3) ( -3, -3) ( -3, -2) ( -3, -1) ( -3, 0) ( -3, 1) ( -3, 2) ( -3, 3) ( -2, 3) ( -1, 3) ( 0, 3) ( 1, 3) ( 2, 3) ( 3, 3) ( 4, 3) ( 4, 2) ( 4, 1) ( 4, 0) ( 4, -1) ( 4, -2) ( 4, -3) ( 4, -4) ( 3, -4) ( 2, -4) ( 1, -4) ( 0, -4) ( -1, -4) ( -2, -4) ( -3, -4) ( -4, -4) ( -4, -3) ( -4, -2) ( -4, -1) ( -4, 0) ( -4, 1) ( -4, 2) ( -4, 3) ( -4, 4) ( -3, 4) ( -2, 4) ( -1, 4) ( 0, 4) ( 1, 4) ( 2, 4) ( 3, 4) ( 4, 4)
center at ( 4, 4)
( 4, 4) ( 5, 4) ( 5, 3) ( 4, 3) ( 3, 3) ( 3, 4) ( 3, 5) ( 4, 5) ( 5, 5) ( 6, 5) ( 6, 4) ( 6, 3) ( 6, 2) ( 5, 2) ( 4, 2) ( 3, 2) ( 2, 2) ( 2, 3) ( 2, 4) ( 2, 5) ( 2, 6) ( 3, 6) ( 4, 6) ( 5, 6) ( 6, 6) ( 7, 6) ( 7, 5) ( 7, 4) ( 7, 3) ( 7, 2) ( 7, 1) ( 6, 1) ( 5, 1) ( 4, 1) ( 3, 1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