문제
https://school.programmers.co.kr/learn/courses/30/lessons/134239
접근 방법 및 풀이
문제 설명에 따라 우박수열을 구한 후 ranges 배열의 내용 대로 면적을 구함
import java.util.ArrayList;
import java.util.List;
public class Q30_134239 {
public double[] solution(int k, int[][] ranges) {
List<Integer> collatzList = this.getCollatzNumbers(k);
double[] integrals = this.getIntegrals(collatzList);
double[] answer = new double[ranges.length];
int collatzLength = collatzList.size();
for (int i = 0; i < ranges.length; i++) {
int[] range = ranges[i];
answer[i] = getIntegral(integrals, range[0], collatzLength + range[1] - 1);
}
return answer;
}
public double getIntegral(double[] integrals, int start, int end) {
if (start == end) {
return 0.0;
} else if (start > end) {
return -1.0;
}
double total = 0;
for (int i = start + 1; i <= end; i++) {
total += integrals[i];
}
return total;
}
public List<Integer> getCollatzNumbers(int number) {
List<Integer> list = new ArrayList<>();
while (true) {
list.add(number);
if (number == 1) {
break;
}
if (number % 2 == 0) {
number = number / 2;
} else {
number = number * 3 + 1;
}
}
return list;
}
public double[] getIntegrals(List<Integer> collatzList) {
int length = collatzList.size();
double[] results = new double[length];
results[0] = 0.0;
for (int i = 1; i < length; i++) {
int x0 = collatzList.get(i - 1);
int x1 = collatzList.get(i);
results[i] = (double) (x0 + x1) / 2.0;
}
return results;
}
}