1 / 5
Jun 29

SPTTRN1 - Straight Line Spiral Pattern (Act 1)

#include
#include
using namespace std;

void drawSpiral(int s) {
vector<vector> grid(s, vector(s, ‘.’));

int layer = 0;

while (true) {
   int top = layer;
    int bottom = s - layer - 1;
    int left = layer;
    int right = s - layer - 1;

    if (top > bottom || left > right)
        break;


    // top row
    for (int i = left; i <= right; i++)
        grid[top][i] = '*';


    // right column
    for (int i = top + 1; i <= bottom; ++i)
        grid[i][right] = '*';

    if (top == bottom && left == right)
        break;

    // bottom row
    for (int i = right - 1; i >= left; --i)
        grid[bottom][i] = '*';

    // left column (leave one space above)
    for (int i = bottom - 1; i > top + 1; --i){
        grid[i][left] = '*';

    }
    layer += 2;


}



for (int i = 0; i < s; ++i) {
    for (int j = 0; j < s; ++j)
        cout << grid[i][j];
    cout << '\n';
}

}

int main() {
int t;
cin >> t;

vector<int> sizes(t);
for (int i = 0; i < t; ++i)
    cin >> sizes[i];

for (int i = 0; i < t; ++i) {
    drawSpiral(sizes[i]);
    cout << '\n';
}

return 0;

}
what is soultion correct to this problem?

For the second test case, the expected answer is

*****
....*
***.*
*...*
*****

but your program gives:

*****
....*
*.*.*
*...*
*****

Do you see the difference?

i know but i tried more than one way to fix this case,but there is also an incorrect case of 78
Can you solve this problem and help me?

#include
#include
using namespace std;

void drawSpiral(int s) {
vector<vector> grid(s, vector(s, ‘.’));

int layer = 0;

while (true) {
    int top = layer;
    int bottom = s - layer - 1;
    int left = layer;
    int right = s - layer - 1;

    if (top > bottom || left > right)
        break;

    // top row
    for (int i = left; i <= right; i++)
        grid[top][i] = '*';

    // right column
    for (int i = top + 1; i <= bottom; ++i)
        grid[i][right] = '*';

    if (top == bottom && left == right)
        break;

    // bottom row
    for (int i = right - 1; i >= left; --i)
        grid[bottom][i] = '*';

    // left column (leave one space above)
    for (int i = bottom - 1; i > top + 1; --i)
        grid[i][left] = '*';

    layer += 2;
  if (s % 2 == 1)

    grid[top+2][left+1] = '*';
}


for (int i = 0; i < s; ++i) {
    for (int j = 0; j < s; ++j)
        cout << grid[i][j];
    cout << '\n';
}

}

int main() {
int t;
cin >> t;

vector<int> sizes(t);
for (int i = 0; i < t; ++i)
    cin >> sizes[i];

for (int i = 0; i < t; ++i) {
    drawSpiral(sizes[i]);
    cout << '\n';
}

return 0;

}

case 78 is an incorrect

while (true) {
    int left = layer;
    ...
    // top row
    for (int i = left; i <= right; i++)
        grid[top][i] = '*';
    ...
    layer += 2;
}

I’m not going to fix your code for you, but I suspect you need to make adjustment to one or more of these lines.