본문 바로가기

TIL/알고리즘 연습

[2022 KAKAO TECH INTERNSHIP] 성격 유형 검사하기

내 풀이

function solution(survey, choices) {

    const scores = [0,0,0,0]
    const mappings = {
        'R' : 0,
        'T' : 0,
        'C' : 0,
        'F' : 0,
        'J' : 0,
        'M' : 0,
        'A' : 0,
        'N' : 0
    }

    choices.map((choice, idx) => {
      const score = choice -4

      if (score > 0) {
          const surveyType = survey[idx][1]
          mappings[surveyType] += score
      }else {
          const surveyType = survey[idx][0]
          mappings[surveyType] -= score
      }
    })

    const mappingArr = Object.entries(mappings)

    mappingArr.forEach(([key,value],idx) => {

        const pos = Math.floor(idx/2)
        const sign = idx%2 ? 1 : -1

        scores[pos] += sign * value 
    })

    let mbti = ''
    scores.map((score,idx) => {
        if (score > 0) {
            mbti += mappingArr[idx*2+1][0]
        } else {
            mbti += mappingArr[idx*2][0]
        }
    })

    return mbti
}

 

오랜만에 푸니 더럽게 풀었고 오래 걸렸다. 근데, 이 문제를 깔끔하게 풀 수 있었을까 잘 모르겠다. 

 


 

정답 코드

function solution(survey, choices) {
    const MBTI = {};
    const types = ["RT","CF","JM","AN"];

    types.forEach((type) =>
        type.split('').forEach((char) => MBTI[char] = 0)
    )

    choices.forEach((choice, index) => {
        const [disagree, agree] = survey[index];

        MBTI[choice > 4 ? agree : disagree] += Math.abs(choice - 4);
    });

    return types.map(([a, b]) => MBTI[b] > MBTI[a] ? b : a).join("");
}

 

새로 배운 점 :

- const [disagree, agree] = survey[index] 이 부분 관찰 좀만 잘했으면 더 이쁘게 할 수 있었을 텐데, 좀 돌아간 거 같다.

- map에서 구조 분해할당을 바로 쓸 수 있는 줄 몰랐다. 실무에서 쓸 수 있을까?