Algorithm - lev2 - 오픈채팅방

ryan·2022년 6월 9일
0

프로그래머스 level2 오픈채팅방

채팅방에 들어오고 나가거나, 닉네임을 변경한 기록이 담긴 문자열 배열 record가 매개변수로 주어질 때, 모든 기록이 처리된 후, 최종적으로 방을 개설한 사람이 보게 되는 메시지를 문자열 배열 형태로 return 하도록 solution 함수를 완성하라.


내 풀이 (100/100)

function solution(record) {
  const answer = [];
  const user = {};
  // user 객체에 uid를 key값으로 두고 value(닉네임)을 계속해서 update하는 형식으로 구현
  record.forEach((e) => {
    const split = e.split(' ');
    if (split[0] !== 'Leave') {user[split[1]] = split[2];} 
    else return;
  });
  
  // swtich문을 통해서 반환문 추출
  record.forEach((e) => {
    const split = e.split(' ');
    switch (split[0]) {
      case 'Enter':
        return answer.push(`${user[split[1]]}님이 들어왔습니다.`);
      case 'Leave':
        return answer.push(`${user[split[1]]}님이 나갔습니다.`);
      default:
        break;
    }
  });
  return answer;
}
  • 처음에는 아래와 같이 reduce로 자료구조(user 객체)를 설계했는데, 같은 결과를 내뱉지만 채점에서 떨어졌다. 아직까지 그 이유를 모르겠다.
  const recordObj = record.reduce((acc, cur, i) => {
    const split = cur.split(' ');
    acc[split[1]] = split[2];
    return acc;
  }, {});

풀이

function solution(record) {
    var answer = [];
    const users = {}
    record.map(history => {
        const [action, id, name] = history.split(' ')
        if(action !== 'Leave') users[id] = name
    })
    record.map(history => {
        const [action, id, name] = history.split(' ')
        if(action === 'Enter') answer.push(`${users[id]}님이 들어왔습니다.`)
        if(action === 'Leave') answer.push(`${users[id]}님이 나갔습니다.`)
    })
    return answer;
}
  • 위 풀이는 새로운 배열을 사용하지 않을 건데 map을 쓴 이유를 잘 모르겠다. 심지어 forEach가 map보다 성능이 더 좋다.
  • 위 풀이에서는 구조분해할당을 split한 return값에 바로 적용했고, 이외의 방식은 동일하다.
profile
프론트엔드 개발자

0개의 댓글