성격 유형 검사하기

이리·2024년 7월 31일
0
post-thumbnail

문제 (프로그래머스 118666 : 성격 유형 검사하기)
181943 : 성격 유형 검사하기

별도 문제 설명 생략

문제파악

  • 주어진 parameter : 문자열 배열 survey, 정수형 배열 choices
  • survey가 무엇을 묻는 것인지 주어지고, 해당 질문의 답이 choices에 주어진다.
  • 같으면 사전상 앞의 것 선택 (RT, CF, JM, AN)

접근방법

  • 4를 기준으로 +- 가 된다. 1==7, 2==6, 3==5
    • Math.abs(chocies[i]-4)
  • 어차피 성격 유형은 4종류밖에 없기 때문에 정수형 배열 [4][2] 만들어서 점수를 배정하면 되지않을까?
  • 문제 유형이 다르다.. (AN도 있고 NA도 있다…) ⇒ 배열로는 어렵겠다..(고정돼있기때문)
    • Map으로 처리한다면? character별 점수를 배정하고 해당하는 characater에 점수를 추가
    • 최종 두개씩 비교(RT, CF, JM, AN)해서 총 4개의 성격유형을 출력

코드구현

import java.util.*;

class Solution {
    public String solution(String[] survey, int[] choices) {
        
        // 총 길이 
        int n = survey.length;
        String answer = "";
        
        // 답변을 넣을 map 
        Map<Character, Integer> scores = new HashMap<>();
        
        scores.put('R', 0);
        scores.put('T', 0);
        scores.put('C', 0);
        scores.put('F', 0);
        scores.put('J', 0);
        scores.put('M', 0);
        scores.put('A', 0);
        scores.put('N', 0);
        
        // survey를 돌면서 점수 추가하기
        for(int i = 0; i<n; i++){
            char c1 = survey[i].charAt(0);
            char c2 = survey[i].charAt(1);
            int choice = choices[i];
            
            if(choice < 4){
                scores.put(c1, scores.get(c1)+(4-choice));
            }else{
                scores.put(c2, scores.get(c2)+(choice-4));
            }
        }
        
        // RT, CF, JM, AN 끼리 값 비교해서 answer에 추가 
        answer += (scores.get('R') >= scores.get('T'))? "R" : "T";
        answer += (scores.get('C') >= scores.get('F'))? "C" : "F";
        answer += (scores.get('J') >= scores.get('M'))? "J" : "M";
        answer += (scores.get('A') >= scores.get('N'))? "A" : "N";
        
        return answer;
    }
}

배운점

  1. 삼항 연산자는 값을 반환할뿐 다른 작업(대입, 문자열 변환)은 할수 없다.

다른 방법은 없을까?

https://school.programmers.co.kr/learn/courses/30/lessons/118666/solution_groups?language=java - 이종한님 코드..

나도 문자가 나눠져있어서 case로 처리할수도있겠다는 생각을 했었는데.. 다들 한번씩 봐보길 바란다..
⇒ 극한의 case…

profile
Bonjour!

0개의 댓글