나선형 배열

2852 단어 수조
function circleNumber(n){
	var re = [];
	
	/**
		1 
		2 
		3 
		4 
	*/
	var currentPos = 1;
	/** 1 xy */
	var xy = null;
	var max = n * n;
	/**
		 
	*/
	function initMap(){
		for(var i= 0 ; i < n ; i++){
			var tmp = [];
			for(var j = 0 ; j < n ; j++ ){
				tmp.push(0);
			}
			re.push(tmp);
		}
	}
	
	/**
		 1 
	*/
	function firstPos(){
		if(n%2 == 1){	//  ,1 
			var posx = parseInt(n/2),
				posy = parseInt(n/2);
			re[posx][posy] = 1;
			xy = {x:posx,y:posy};
		}else{
			var posx = parseInt((n-1)/2),
				posy = parseInt((n-1)/2);
			re[posx][posy] = 1;
			xy = {x:posx,y:posy};
		}
	}
	
	/**
		 
	*/
	function step(){
		var n = 2;
		
		while(n <= max){	
			switch(currentPos){
				case 1:// 
					if(re[xy.x][xy.y+1] == 0){
						re[xy.x][xy.y+1] = n;
						n++;
						xy = {x:xy.x,y:xy.y+1};
						currentPos++;
					}else{
						if(currentPos == 1){
							currentPos = 4;
						}else{
							currentPos--;
						}
					}
					break;
				case 2:// 
					if(re[xy.x+1][xy.y] == 0){
						re[xy.x+1][xy.y] = n;
						xy = {x:xy.x+1,y:xy.y};
						currentPos++;
						n++;
					}else{
						if(currentPos == 1){
							currentPos = 4;
						}else{
							currentPos--;
						}
					}
					break;
				
				case 3://
					if(re[xy.x][xy.y-1] == 0){
						re[xy.x][xy.y-1] = n;
						xy = {x:xy.x,y:xy.y-1};
						currentPos++;
						n++;
					}else{
						if(currentPos == 1){
							currentPos = 4;
						}else{
							currentPos--;
						}
					}
					break;
				case 4://
					if(re[xy.x-1][xy.y] == 0){
						re[xy.x-1][xy.y] =n;
						xy = {x:xy.x-1,y:xy.y};
						currentPos = 1;
						n++;
					}else{
						if(currentPos == 1){
							currentPos = 4;
						}else{
							currentPos--;
						}
					}
					break;
				default:
					break;
			}
		}
		console.log("end");
	}
	
	initMap();
	firstPos();
	step();
	print();
	
	/**
		 
	*/
	function print(){
		var msg = "";
		for(var i = 0 ; i < re.length ; i++){
			for(var j = 0 ; j < re[i].length ; j++){
				msg += " "+re[i][j];
			}
			msg += "
"; } alert(msg); } } circleNumber(3);

 
 
코드를 console에 복사하여 실행하면 된다

좋은 웹페이지 즐겨찾기