본문 바로가기
lecture.js/algorithm.log

#005 모래시계 배열

by malda 2017. 7. 10.
# 문제)
5X5 배열을 이용하여 아래와 같은 모래시계 배열을 만들어라

1
2
3
4
5

6
7
8



9



10
11
12

13
14
15
16
17


이번에도 규칙성을 찾아보자

규칙성1)
첫번째는 0, 1, 2, 3, 4까지 모두 순차 입력되었고
두번째는 1, 2, 3까지 입력되었고 (앞,뒤 1씩 모자름)
세번째는 2까지 (앞,뒤 2씩모자름)
네번째는 다시 1, 2, 3 (앞뒤 1씩 모자름)
다섯번째에서는 모두 입력되었다.

규칙성2)
다행히 row에 변화는 없으며
다만 row가 개행될때마다 앞뒤 빈칸이 1개씩 늘어났다가 
중간 지점에서 줄어드는 것을 알 수 있다.

규칙성3)
중간지점을 기점으로 방향성(증감식)이 변한다는 것을 알 수 있다.
중간지점은 배열크기/2를 통해 구할 수 있다.


package dataStructure.prediction.array;

public class HourGlassArray {
   
    private int[][] array = new int[5][5];
   
    public void execute() {
        int mid = array.length/2;
        int number = 1;
        int depth = 0;
        int direction = 1;
        for(int row=0; row<5; row++) {
            for(int col=depth; col < 5-depth; col++) {
              array[row][col] = number++; 
            }
            if(mid == row) {
                direction *= -1;
            }
            depth += direction;
        }
    }
   
    public void print() {
        for(int row=0; row<5; row++) {
            for(int col=0; col<5; col++) {
                System.out.printf("%3d",array[row][col]);
            }
            System.out.println();
        }
    }
   
    public static void main(String[] args) {
        // TODO Auto-generated method stub
       HourGlassArray hourGlassArray = new HourGlassArray();
       hourGlassArray.execute();
       hourGlassArray.print();
    }

}




'lecture.js > algorithm.log' 카테고리의 다른 글

#007 배열 회전  (0) 2017.07.10
#006 열우선 배열  (0) 2017.07.10
#004 ㄹ 배열  (0) 2017.07.10
#003 달팽이 배열  (0) 2017.07.10
#002 등차 수열 구하기  (0) 2017.07.10