N과 K를 입력받아 N개의 수를 입력받고 뒷수-앞수의 값들을 순회하면서 계산한다.
이 과정을 K번 진행했을 때의 결과를 ',' 기호를 붙여서 출력한다.
import java.io.*;
import java.util.*;
public class Sequence {
static int N, K; // 입력 받는 수
static ArrayList<Integer> array = new ArrayList<>(); // 입력받은 숫자들을 저장
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
N = Integer.parseInt(st.nextToken());
K = Integer.parseInt(st.nextToken());
st = new StringTokenizer(br.readLine());
for (String number : st.nextToken().split(","))
array.add(Integer.parseInt(number)); // ArrayList에 넣기
calculateSeq(0); // 재귀함수 호출
// 문자 replace하여 결과값 포멧 바꾸기
String result = array.toString().replace("[", "").replace("]", "").replace(", ", ",");
System.out.println(result);
}
public static void calculateSeq(int depth) {
// K번 반복 후 종료
if (depth == K)
return;
// 점화식 이용하여 값 계산후 ArrayList에 값 바꾸기
for (int i = 0; i < array.size() - 1; i++)
array.set(i, array.get(i + 1) - array.get(i));
// ArrayList 마지막 값 제거
array.remove(array.size() - 1);
// 다시 호출
calculateSeq(depth + 1);
}
}