[프로그래머스] 종이접기::알고리즘

2020. 6. 19. 13:02algorithm/array

몇 번 접는지에 따라서 펼쳤을 때, 어느 방향으로 접혔는지 이진 배열을 만들어내는 것

 

n = 3 일 때,

 

n = 1 -> 0

n = 2 -> 0 0 1

n = 3 -> 0 0 1 0 0 1 1

 

1. n의 숫자를 보면 n - 1의 숫자가 자릿수 그대로 내려오고,

2. 반으로 접은 부분은 0이고,

3. 파란색으로 칠해진 부분의 숫자가 뒤집혀져서 넘어가는 것을 확인할 수 있다.

 

 

Java 코드

 

import java.util.Arrays;

public class Solution_종이접기 {

	public static int[] solution(int n) {
		int len = 1;
		int[] answer = new int[len];
		
		for (int i = 1; i < n; ++i) {
			int len_temp = len * 2 + 1;
			int[] arr_temp = new int[len_temp];
			
			for (int j = 0; j < len; ++j)
				arr_temp[j] = answer[j];
			arr_temp[len] = 0;
			for (int j = 1; j <= len; ++j) {
				if (answer[len - j] == 0)
					arr_temp[len + j] = 1;
			}
			
			len = len_temp;
			answer = arr_temp;
		}
		
		return answer;
	}
	
	public static void main(String[] args) {
		System.out.println(Arrays.toString(solution(1)));
		System.out.println(Arrays.toString(solution(2)));
		System.out.println(Arrays.toString(solution(3)));
		System.out.println(Arrays.toString(solution(4)));
	}

}

'algorithm > array' 카테고리의 다른 글

[프로그래머스] 자물쇠와 열쇠::알고리즘  (4) 2020.06.19