231207 우박수열 정적분

Jongleee·2023년 12월 7일
0

TIL

목록 보기
436/737
public double[] solution(int k, int[][] ranges) {
	List<Double> collatz = generateCollatzSequence(k);
	Double[] collatzNumber = toDouble(collatz);

	double[] areaSum = calculateAreaSum(collatzNumber);
	double[] answer = new double[ranges.length];

	for (int i = 0; i < ranges.length; i++) {
		int start = ranges[i][0];
		int end = collatzNumber.length + ranges[i][1] - 1;

		if (end > start) {
			answer[i] = areaSum[end] - areaSum[start];
		} else if (end == start) {
			answer[i] = 0;
		} else {
			answer[i] = -1;
		}
	}

	return answer;
}

private Double[] toDouble(List<Double> collatz) {
	return collatz.toArray(new Double[0]);
}

private List<Double> generateCollatzSequence(int k) {
	List<Double> collatz = new ArrayList<>();
	while (k > 1) {
		collatz.add((double) k);
		k = (k % 2 == 0) ? k / 2 : 3 * k + 1;
	}
	collatz.add(1.0);
	return collatz;
}

private double[] calculateAreaSum(Double[] collatzNumber) {
	double[] areaSum = new double[collatzNumber.length];
	areaSum[0] = 0;

	for (int i = 1; i < collatzNumber.length; i++) {
		areaSum[i] = (collatzNumber[i - 1] + collatzNumber[i]) / 2 + areaSum[i - 1];
	}

	return areaSum;
}

출처:https://school.programmers.co.kr/learn/courses/30/lessons/134239

0개의 댓글