이것 저것 삽질로 인해 쉬운데 못 푼 코테 문제 기억하고 다시 풀었다.
배열이 [1,2,3,4,5,6] 이렇게 들어오면 분할하면서 뒤집어서 합치는 문제이다.
[1,2,3,4,5,6] ----> [6,5,4,3,2,1]
[6,5,4,3,2,1] ----> [6,5,4] [3,2,1]
[6,5,4][3,2,1] ----> [4,5,6] [1,2,3]
[4,5,6] [1,2,3] ----> [4,5] [6] [1,2] [3]
[4,5] [6] [1,2] [3] ----> [5,4] [6] [2,1] [3]
[5,4] [6] [2,1] [3] ----> [5] [4] [6] [2] [1] [3]
[5] [4] [6] [2] [1] [3] ----> [5,4,6,2,1,3]
이런식으로 진행된다.
import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
class Main {
static List<Integer> answer;
public static void main(String[] args) {
int[] input = {1,2,3,4,5,6};
List<Integer> inputList = Arrays.stream(input).boxed().collect(Collectors.toList());
answer = new ArrayList<>();
divAndConq(inputList);
System.out.println(answer);
}
public static void divAndConq(List<Integer> inputList) {
if(inputList.size() == 1) {
answer.add(inputList.get(0));
} else {
Collections.reverse(inputList);
int len = inputList.size() % 2 == 0 ? inputList.size() / 2 : inputList.size() / 2 + 1;
List<Integer> front = new ArrayList<>();
List<Integer> back = new ArrayList<>();
for(int i = 0; i < inputList.size(); i++) {
if(i < len)
front.add(inputList.get(i));
else
back.add(inputList.get(i));
}
divAndConq(front);
divAndConq(back);
}
}
}