Spiral Numbers

Print spiral number array like this:

7 8 9 10
6 1 2 11
5 4 3 12

Given coordinates of a point, find the corresponding number residing on it.

There are many solutions to this problem. For example, find the number by looking for the relation(function) between the number and its coordinates. The code below solves the problem without using such kind of relation. Of course, the cost is the increase of running time.



int spiralNumber( int X, int Y) // coordinates ( X, Y) 
{   int num = 1;
    if ( X == 0 && Y == 0) return num;

    int flag = 1; // Horizontal =1, Vertical =-1
    int dH = 1; // Horizontal right = 1, left = -1
    int dV = 1;  // Vertical downward = 1, up = -1
    int step;   // 1 1 2 2 3 3 4 4 5 5 ...
    int x = 0, y = 0; 

    //  for ( int k = 2, step = 1; (x != X ) && ( y != Y);  ++k, step = k/2 )
    for( int k=2; !((x == X) && (y == Y)); ++k )
    {
        step = k/2; 
        //cout << step;
        if ( 1 == flag )
        {
            for ( int i = 0; i < step; i++ )
            {
                if ( !((x == X) && (y == Y)) )
                {
                    x += dH; 
                    num++;
                }
            }
            dH *= (-1);
        }
        else 
        {
            for ( int i = 0; i < step; i++ )
            {
                if ( !((x == X) && (y == Y)) )
                {
                    y += dV; 
                    num++;
                }   
            }     
            dV *= (-1);
        }
        if ( !(x == 0 && y == 0) ) flag *= (-1);
    }
    return num;
}

void printSpiralArray(int N)
{
    for (int j = -N+1; j < N; ++j)
    {
        for (int l = -N+1; l < N; ++l)
        {
            cout << setw(5) <<  spiralNumber(l,j ) << " " ; 
        }
        cout << '\n' ;
    }
    cout << endl;
}

No comments: