달팽이배열

카테고리 없음 2014. 11. 28. 11:44 |


2가지 구현
 

001// Snail.cpp : Defines the entry point for the console application.
002//
003 
004#include <WINDOWS.H>
005#include <MATH.H>
006#include <STDLIB.H>
007 
008void printXY(char * pszText , short x, short y)
009{
010    COORD pos = {x, y};
011    HANDLE hConsole_c = GetStdHandle(STD_OUTPUT_HANDLE);
012    DWORD len = strlen(pszText);
013    DWORD dwBytesWritten = 0;
014    WriteConsoleOutputCharacter(hConsole_c, pszText, len, pos, &dwBytesWritten);
015}
016 
017int Sum(int x, int y , int size)
018{
019    int sum = 0;
020    for (int i = 0; i < (x>y?y:x) ; i++,size--)
021    {
022        sum += --size;
023    }
024    return sum*4;
025}
026 
027void Work1(int size)
028{
029    int x=-1,y=0;
030    int inValue = 1;
031    char szText[10];
032    enum D{
033        DOWN,RIGHT,UP,LEFT
034             
035    };
036    D d = DOWN;
037    for (int i = 0; i < size ; i++)
038    {
039        sprintf(szText,"% 3d",inValue++);
040        printXY(szText,++x*3,0);
041    }
042    size--;
043    while(size > 0)
044    {
045        for (int k = 0; k < size ; k++)
046        {
047            switch (d)
048            {
049            case DOWN:
050                y++;
051                break;
052            case RIGHT:
053                x--;
054                break;
055            case UP:
056                y--;
057                break;
058            case LEFT:
059                x++;
060                break;
061            }
062            sprintf(szText,"% 3d",inValue++);
063            printXY(szText,x*3,y);
064        }
065        size-=d%2;
066        d = D((d+1)%4);
067         
068    }
069}
070 
071void Work2(int inSize)
072{
073    int inValue;
074    double inSize2 = inSize-1;
075    char szText[10];
076    for (double x = 0; x < inSize  ; x++)
077    {
078        for (double y = 0; y < inSize  ; y++)
079        {
080            int dx = abs(fabs(x - inSize2*0.5) - inSize2*0.5);
081            int dy = abs(fabs(y - inSize2*0.5) - inSize2*0.5);
082            int cor = dx > dy ? dy:dx ;
083            cor *= 2;
084            if(y-x <= 0)
085            {
086                inValue = Sum(dx,dy,inSize) + 1+x+y - cor;
087            }else
088            {
089                inValue = Sum(dx+1,dy+1,inSize) + 1 -x-y + cor;
090            }
091             
092            sprintf(szText,"% 3d",inValue);
093            printXY(szText,x*3,y);
094        }
095    }
096}
097int main(int argc, char* argv[])
098{
099    int size;
100    int work;
101    printf("input size : ");
102    scanf("%d",&size);
103    //Work1(size);
104    printf("select work[1 , 2] : ");
105    scanf("%d",&work);
106    system("cls");
107    switch(work)
108    {
109    case 1:
110        Work1(size);
111        break;
112    case 2:
113        Work2(size);
114        break;
115    }
116    getchar();
117    getchar();
118    return 0;
119}


Posted by 동적할당
: