이번 문제는 이렇게 푸는게 맞나..? 싶었던 문제였다.
Map에 하나하나 담아줄 때 이렇게 하는게 맞나 싶었는데 다른 방법도 있겠지만 제일 먼저 생각난 방법이 이거였다.
변수 초기화 : 모든 성격 유형의 점수를 저장할 Map<String, Integer> 객체를 만든 후, 각 성격 유형의 점수를 초기화한다.
Map<String, Integer> result = new HashMap<>();
result.put("R", 0); result.put("T", 0);
result.put("C", 0); result.put("F", 0);
result.put("J", 0); result.put("M", 0);
result.put("A", 0); result.put("N", 0);
응답 처리 : survey 배열을 순회하면서 각 질문에 대한 사용자의 선택을 기반으로 점수를 계산한다.
choices 값에 따라 해당 성격 유형의 점수를 부여한다.
- 선택지가 4보다 크면 (즉, 동의하는 경우), 두 번째 성격 유형에 choices[i] - 4 점을 부여한다.
- 선택지가 4보다 작으면(즉, 비동의하는 경우), 첫 번째 성격 유형에 4 - choices[i] 점을 부여한다.
for(int i = 0; i < survey.length; i++) {
String firstType = survey[i].substring(0, 1);
String secondType = survey[i].substring(1, 2);
if(choices[i] > 4) {
result.replace(secondType, result.get(secondType) + choices[i] - 4);
} else if(choices[i] < 4) {
result.replace(firstType, result.get(firstType) + 4 - choices[i]);
}
}
성격 유형 결정 : 각 지표에 대해 더 높은 점수를 받은 유형을 결정한다. 만약 두 성격 유형의 검사 점수가 같다면
사전순으로 빠른 성격 유형을 선택한다.
if(result.get("R") >= result.get("T")) sb.append("R");
else sb.append("T");
if(result.get("C") >= result.get("F")) sb.append("C");
else sb.append("F");
if(result.get("J") >= result.get("M")) sb.append("J");
else sb.append("M");
if(result.get("A") >= result.get("N")) sb.append("A");
else sb.append("N");
결과 반환 : 최종적으로 결과를 반환한다.
아래는 최종 코드이다.
import java.util.*;
class Solution {
public String solution(String[] survey, int[] choices) {
StringBuilder sb = new StringBuilder();
Map<String, Integer> result = new HashMap<>();
result.put("R", 0); result.put("T", 0);
result.put("C", 0); result.put("F", 0);
result.put("J", 0); result.put("M", 0);
result.put("A", 0); result.put("N", 0);
for(int i = 0; i < survey.length; i++) {
String firstType = survey[i].substring(0, 1);
String secondType = survey[i].substring(1, 2);
if(choices[i] > 4) {
result.replace(secondType, result.get(secondType) + choices[i] - 4);
} else if(choices[i] < 4) {
result.replace(firstType, result.get(firstType) + 4 - choices[i]);
}
}
if(result.get("R") >= result.get("T")) sb.append("R");
else sb.append("T");
if(result.get("C") >= result.get("F")) sb.append("C");
else sb.append("F");
if(result.get("J") >= result.get("M")) sb.append("J");
else sb.append("M");
if(result.get("A") >= result.get("N")) sb.append("A");
else sb.append("N");
return sb.toString();
}
}