simDev1234
심플하고 차분하게
simDev1234
전체 방문자
오늘
어제
  • 분류 전체보기
    • Computer Science
      • Basic Math
      • Data Structure
      • Algorithm
      • Database
      • OS
    • Language
      • Java
      • Kotlin
      • SQL
    • Framework
      • Spring
      • Orm&Mapper
      • 프로젝트로 스프링 이해하기
      • 스프링 라이브러리
    • Infra
      • Cloud
      • Docker
      • Redis
      • AWS, Azure
      • Device
    • Etc
      • CleanCoding
    • Git,Github

블로그 메뉴

  • 홈
  • 태그
  • 방명록

공지사항

인기 글

태그

  • 자바프로그래밍
  • 자바메모리구조
  • 404
  • 스프링
  • scanner #next() #nextLine()
  • 컨트롤러
  • 자바
  • null
  • controllerTest
  • 참조타입
  • 참조변수
  • JVM메모리구조
  • 자바프로그램

최근 댓글

최근 글

티스토리

hELLO · Designed By 정상우.
simDev1234

심플하고 차분하게

Language/Java

[자바_예제] 2차원 배열 _ 달팽이(snail) 배열

2022. 3. 28. 09:25

>> 실행결과

차수 : 5
---snail1---
[   1   2   3   4   5]
[  16  17  18  19   6]
[  15  24  25  20   7]
[  14  23  22  21   8]
[  13  12  11  10   9]
---snail2---
[  25  24  23  22  21]
[  10   9   8   7  20]
[  11   2   1   6  19]
[  12   3   4   5  18]
[  13  14  15  16  17]
또?(y/n) : n
----END----

[Snail 객체]

package myutil;

public class Snail {
	//Right -> Down -> Left -> Up
	//이 과정을 반복하되,
	//만약 움직이려는 방향에 값이 있을 경우, 현재 자리에서 이동하지 않고,
	 //값을 넣지 않고 방향을 전환한다.
	//Right : col++
	//Down : row++
	//Left : col__
	//Up : row--
	
	//이동 정보에 대한 상수 선언
	public static final int RIGHT = 1;
	public static final int DOWN = 2;
	public static final int LEFT = 3;
	public static final int UP = 4;
	
	//현재 이동 방향 정보를 저장할 변수
	int direction;
	
	int chasu;	
	int[][] snail_array;
	
	public void setChasu(int chasu) {
		this.chasu = chasu;
		
		System.out.println("---snail1---");
		
		//달팽이 만들기
		make_snail();
		
		//출력
		display();
		
		System.out.println("---snail2---");
		
		//달팽이 만들기
		make_snail2();
		
		//출력
		display();
	}
	
	private void make_snail() {
		//달팽이 배열 생성
		snail_array = new int[chasu][chasu];
		
		int row = 0;
		int col = -1;
		int su = 1;
		
		direction = RIGHT;
		
		//[0][0]부터 채워나가기
		for(int i = 0; i < chasu*chasu; i++) {
			if(direction == RIGHT) { //오른쪽 채우기
				col++;
				if(col == chasu || snail_array[row][col]!=0) {//이동하다 막히면
					row++;
					col--;
					direction = DOWN;
				}
			}else if(direction == DOWN) { //아래쪽 채우기
				row++;
				if(row == chasu || snail_array[row][col]!=0) {
					row--;
					col--;
					direction = LEFT;
				}
			}else if(direction == LEFT) { //왼쪽 채우기
				col--;
				if(col < 0 || snail_array[row][col]!=0) {
					row--;
					col++;
					direction = UP;
				}
			}else if(direction == UP) {//위쪽 채우기
				row--;
				if(snail_array[row][col]!=0) {
					row++;
					col++;
					direction = RIGHT;
				}
			}
			
			snail_array[row][col] = su++;
		}//end for()
	}//end snail()
	
	private void make_snail2() {
		//달팽이 배열 생성
		snail_array = new int[chasu][chasu];
		
		int row = 0;
		int col = -1;
		int su = chasu*chasu;
		
		direction = RIGHT;
		
		//[0][0]부터 채워나가기
		for(int i = 0; i < chasu*chasu; i++) {
			if(direction == RIGHT) { //오른쪽 채우기
				col++;
				if(col == chasu || snail_array[row][col]!=0) {//이동하다 막히면
					row++;
					col--;
					direction = DOWN;
				}
			}else if(direction == DOWN) { //아래쪽 채우기
				row++;
				if(row == chasu || snail_array[row][col]!=0) {
					row--;
					col--;
					direction = LEFT;
				}
			}else if(direction == LEFT) { //왼쪽 채우기
				col--;
				if(col < 0 || snail_array[row][col]!=0) {
					row--;
					col++;
					direction = UP;
				}
			}else if(direction == UP) {//위쪽 채우기
				row--;
				if(snail_array[row][col]!=0) {
					row++;
					col++;
					direction = RIGHT;
				}
			}
			
			snail_array[row][col] = su--;
		}//end for()
	}

	public void display() {
		for(int i = 0; i < chasu; i++) {
			System.out.print("[");
			for(int j = 0; j < chasu; j++) {
				System.out.printf("%4d",snail_array[i][j]);
			}
			System.out.print("]");
			System.out.println();
		}//end for()
	}
}//end Snail

[Main 함수]

package mymain;

import java.util.Scanner;
import myutil.Snail;

public class _11_Question_Snail {
	public static void main(String[] args) {
		Scanner scanner = new Scanner(System.in);
		int chasu;
		String yn = "y";
		Snail snail = new Snail();
		
		while(true) {
			System.out.print("차수 : ");
			chasu = scanner.nextInt();
						
			//달팽이 객체 - 차수 전달(setter)
			snail.setChasu(chasu);
			//달팽이 출력
			
			//또?
			System.out.print("또?(y/n) : ");
			yn = scanner.next();
			if(!yn.equalsIgnoreCase("y")) break;
		}//end while
		
		System.out.println("----END----");
		scanner.close();
	}//end main
	
}

'Language > Java' 카테고리의 다른 글

[자바_API] 네트워킹  (0) 2022.04.04
[자바의정석_복습] 예외처리  (0) 2022.03.28
[자바_예제] 2차원 배열_로또 추첨  (0) 2022.03.28
[자바API_AWT/Swing] 키보드 이벤트 구현하기  (0) 2022.03.28
[자바API_AWT/Swing] 버튼 이벤트 구현하기  (0) 2022.03.28
    'Language/Java' 카테고리의 다른 글
    • [자바_API] 네트워킹
    • [자바의정석_복습] 예외처리
    • [자바_예제] 2차원 배열_로또 추첨
    • [자바API_AWT/Swing] 키보드 이벤트 구현하기
    simDev1234
    simDev1234
    TIL용 블로그. * 저작권 이슈가 있는 부분이 있다면 댓글 부탁드립니다.

    티스토리툴바