코드 그라데이션

Day11. 달팽이 모양 배열 출력하기 chat GPT 설명 본문

Java/Mega

Day11. 달팽이 모양 배열 출력하기 chat GPT 설명

완벽한 장면 2023. 3. 25. 13:42
public class HW03 {
    public static void main(String[] args) {
        int[][] arr = new int[5][5];

        int count = 1;
        int rowStart = 0, rowEnd = 4, colStart = 0, colEnd = 4;

        while (count <= 25) {
            // 오른쪽으로 이동
            for (int i = colStart; i <= colEnd; i++) {
                arr[rowStart][i] = count++;
            }
            rowStart++;

            // 아래쪽으로 이동
            for (int i = rowStart; i <= rowEnd; i++) {
                arr[i][colEnd] = count++;
            }
            colEnd--;

            // 왼쪽으로 이동
            for (int i = colEnd; i >= colStart; i--) {
                arr[rowEnd][i] = count++;
            }
            rowEnd--;

            // 위쪽으로 이동
            for (int i = rowEnd; i >= rowStart; i--) {
                arr[i][colStart] = count++;
            }
            colStart++;
        }

        // 출력하기
        for (int i = 0; i < 5; i++) {
            for (int j = 0; j < 5; j++) {
                System.out.printf("%02d ", arr[i][j]);
            }
            System.out.println();
        }
    }
}

 

출력 결과

01 02 03 04 05 
16 17 18 19 06 
15 24 25 20 07 
14 23 22 21 08 
13 12 11 10 09

 

 

 

 

 

 

이걸 내 나름대로 이중 for문 써서 만든 코드

int count = 1;

for (int i = rowStart; i <= rowEnd; i++) {
  arr[i][colStart] = count++;
}
colStart++;

for (int i = colStart; i <= colEnd; i++) {
  arr[rowEnd][i] = count++;
}
rowEnd--;

for (int i = rowEnd; i >= rowStart; i--) {
  arr[i][colEnd] = count++;
}
colEnd--;

for (int i = colEnd; i >= colStart; i--) {
  arr[rowStart][i] = count++;
}
rowStart++;

// 출력하기
for (int i = 0; i < arr.length; i++) {
  for (int j = 0; j < arr[i].length; j++) {
    System.out.printf("%02d ", arr[i][j]);
  }
  System.out.println();
}

 

728x90
Comments