programmers_우박수열 정적분_java
2023. 5. 21. 18:05ㆍAlgorithm/Programmers
728x90
https://school.programmers.co.kr/learn/courses/30/lessons/134239
import java.util.*;
class Solution {
public double[] solution(int k, int[][] ranges) {
double[] answer = new double[ranges.length];
int[] graph = collatz(k);
int graphtSize = graph.length;
double[] area = calArea(graph);
int answerIdx = 0;
for (int[] r : ranges){
int[] range = calRange(r, graphtSize-1);
if (range[0] > range[1]){
answer[answerIdx] = -1.0;
}else{
answer[answerIdx] = area[range[1]] - area[range[0]];
}
answerIdx++;
}
return answer;
}
// 콜라츠 추측
public int[] collatz(int k){
List<Integer> list = new ArrayList<>();
list.add(k);
while(k > 1){
if (k % 2 == 0){
k = k/2;
}else {
k = k*3 + 1;
}
list.add(k);
}
return listTointArray(list);
}
// List -> Array
public int[] listTointArray(List<Integer> list){
int[] arr = new int[list.size()];
int idx = 0;
for (int i : list){
arr[idx++] = i; // y좌표
}
return arr;
}
// 각 점까지의 영역 합 구하기
public static double[] calArea(int[] graph){
int graphLength = graph.length;
double[] area = new double[graphLength];
int beforeY = graph[0];
for (int i = 1; i<graphLength; i++){
int big = Math.max(beforeY, graph[i]);
int small = Math.min(beforeY, graph[i]);
// 사각형 영역
area[i] += small;
// 삼각형 영역
if (big!=small){ // 같은 값인경우 = 사각형
area[i] += 0.5 * 1 * (big-small);
}
area[i] += area[i-1];
beforeY = graph[i];
}
return area;
}
// 정적분 범위 계산
public int[] calRange(int[] range, int lastIdx){
int[] r = new int[2];
r[0] = range[0];
r[1] = lastIdx + range[1];
return r;
}
}
'Algorithm > Programmers' 카테고리의 다른 글
programmers_두 원 사이의 정수 쌍_java (0) | 2023.05.21 |
---|---|
programmers_리코쳇 로봇_java (0) | 2023.05.21 |
programmers_N-Queen_java (0) | 2023.05.19 |
programmers_시소 짝꿍_java (0) | 2023.05.18 |
programmers_테이블 해시 함수_java (0) | 2023.05.17 |