U E D R , A S I H C RSS

Random Walk/변준원

~cpp 
#include<iostream> 
#include<ctime> 
using namespace std; 
 
int main() 
{ 
        const int max=5; 
        int matrix[max][max]; 
        for(int i=0;i<5;i++) 
        { 
                for(int j=0;j<5;j++) 
                        matrix[i][j]=0; 
        } 
         
        srand(time(0));      // 바퀴벌레 랜덤 놓기 
        int x = rand() % 5; 
        int y = rand() % 5; 
        int p, q;
		matrix[x][y]=1; 
        
		int count=0, number=0;//엔딩수, 이동수 지정
		while(count<24)
		{
			int moving = rand() % 8;
			if (moving==0) //북
				p=0,q=-1;
			else if(moving == 1) //북동
				p=1,q=-1;
			else if(moving == 2)//동
				p=1,q=0;
			else if(moving == 3) //남동
				p=1,q=1;
			else if(moving == 4) //남
				p=0,q=-1;
			else if(moving == 5) //남서
				p=-1,q=1;
			else if(moving == 6) //서
				p=-1,q=0;
			else if(moving == 7) //북서
				p=-1,q=-1;
			x = x + p; 
			y = y + q; 
			if((x<=4 && x>=0) && (y<=4 && y>=0)) // 틀 안쪽인지를 검사
			{
				if(matrix[x][y]==0) //자리 확인
				{	
					matrix[x][y]=matrix[x][y]+1;
					count++;
					number++;
				}

				else
				{
					matrix[x][y]=matrix[x][y]+1;
					number++;
				}
			}
			else // 틀 밖일때 바퀴 되 돌리기
			{
				x=x-p;
				y=y-q;
			}
		};	
		for(int ga=0;ga<5;ga++) 
        { 
			for(int se=0;se<5;se++) 
				cout << matrix[ga][se] << "\t"; 
			cout<<endl;
        } 
		cout<<endl;

		cout << "바퀴벌레의 이동횟수는 " << number << "입니다." << endl;                
		
         
         
	return 0;        

} 
Valid XHTML 1.0! Valid CSS! powered by MoniWiki
last modified 2021-02-07 05:27:51
Processing time 0.0141 sec