달팽이배열

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


2가지 구현
 

// Snail.cpp : Defines the entry point for the console application.
//

#include <WINDOWS.H>
#include <MATH.H>
#include <STDLIB.H>

void printXY(char * pszText , short x, short y)
{
	COORD pos = {x, y};
	HANDLE hConsole_c = GetStdHandle(STD_OUTPUT_HANDLE);
	DWORD len = strlen(pszText);
	DWORD dwBytesWritten = 0;
	WriteConsoleOutputCharacter(hConsole_c, pszText, len, pos, &dwBytesWritten);
}

int Sum(int x, int y , int size)
{
	int sum = 0;
	for (int i = 0; i < (x>y?y:x) ; i++,size--)
	{
		sum += --size;
	}
	return sum*4;
}

void Work1(int size)
{
	int x=-1,y=0;
	int inValue = 1;
	char szText[10];
	enum D{
		DOWN,RIGHT,UP,LEFT
			
	};
	D d = DOWN;
	for (int i = 0; i < size ; i++)
	{
		sprintf(szText,"% 3d",inValue++);
		printXY(szText,++x*3,0);
	}
	size--;
	while(size > 0)
	{
		for (int k = 0; k < size ; k++)
		{
			switch (d)
			{
			case DOWN:
				y++;
				break;
			case RIGHT:
				x--;
				break;
			case UP:
				y--;
				break;
			case LEFT:
				x++;
				break;
			}
			sprintf(szText,"% 3d",inValue++);
			printXY(szText,x*3,y);
		}
		size-=d%2;
		d = D((d+1)%4);
		
	}
}

void Work2(int inSize)
{
	int inValue;
	double inSize2 = inSize-1;
	char szText[10];
	for (double x = 0; x < inSize  ; x++)
	{
		for (double y = 0; y < inSize  ; y++)
		{
			int dx = abs(fabs(x - inSize2*0.5) - inSize2*0.5);
			int dy = abs(fabs(y - inSize2*0.5) - inSize2*0.5);
			int cor = dx > dy ? dy:dx ;
			cor *= 2;
			if(y-x <= 0)
			{
				inValue = Sum(dx,dy,inSize) + 1+x+y - cor;
			}else
			{
				inValue = Sum(dx+1,dy+1,inSize) + 1 -x-y + cor;
			}
			
			sprintf(szText,"% 3d",inValue);
			printXY(szText,x*3,y);
		}
	}
}
int main(int argc, char* argv[])
{
	int size;
	int work;
	printf("input size : ");
	scanf("%d",&size);
	//Work1(size);
	printf("select work[1 , 2] : ");
	scanf("%d",&work);
	system("cls");
	switch(work)
	{
	case 1:
		Work1(size);
		break;
	case 2:
		Work2(size);
		break;
	}
	getchar();
	getchar();
	return 0;
}



Posted by 동적할당
: