[프로그래머스 lev2/JS] 오픈채팅방

woolee의 기록보관소·2022년 11월 7일
0

알고리즘 문제풀이

목록 보기
46/178

문제 출처

프로그래머스 lev2 - 오픈채팅방

문제

나의 풀이

answer 배열에 id로 먼저 넣은 뒤,
만들어 놓은 id 객체를 순회하면서 id를 닉네임으로 바꾸기

function solution(record) {
  let answer = [];
  let id = {};

  for (let i=0; i<record.length; i++) {
    record[i]=record[i].split(' ')

    if (record[i][0] === 'Enter') {
      id[record[i][1]]=record[i][2];
      answer.push(`${record[i][1]}+님이 들어왔습니다.`);
    }
    else if (record[i][0] === 'Leave') {
      answer.push(`${record[i][1]}+님이 나갔습니다.`);
    }
    else if (record[i][0] === 'Change') {
      id[record[i][1]]=record[i][2];
    }
  }

  for (let i=0; i<answer.length; i++) {
    answer[i]=answer[i].split('+');
    answer[i][0] = id[answer[i][0]];
    answer[i]=answer[i].join('');
  }

  return answer;
}

console.log(
  solution(
    [
      "Enter uid1234 Muzi", 
      "Enter uid4567 Prodo", 
      "Leave uid1234", 
      "Enter uid1234 Prodo", 
      "Change uid4567 Ryan"]));

다른 풀이

어차피 결국 닉네임을 업데이트하는 방식이므로, 나처럼 다시 또 for문을 순회하는 게 아니라 한번의 순회에서 닉네임이 있으면, 그걸로 업데이트해주는 방식이 더 효율적이다.

function solution(record) {
    const userInfo = {};
    const action = [];
    const stateMapping = {
        'Enter': '님이 들어왔습니다.',
        'Leave': '님이 나갔습니다.'
    }

    record.forEach((v) => {
        const [state, id, nick] = v.split(' ');

        if(state !== "Change") {
            action.push([state, id]);
        }

        if(nick) {
            userInfo[id] = nick;
        }
    })

    return action.map(([state, uid]) => {
        return `${userInfo[uid]}${stateMapping[state]}`;    
    })
}

map

function solution(record) {
    let ret = []
    const uids = new Map()

    record.forEach(entry => {
        let [command, uid, nick] = entry.split(' ')
        if (command === 'Enter' || command === 'Change') uids.set(uid, nick)
    })

    record.forEach(entry => {
        let [command, uid] = entry.split(' ')
        if (command === 'Enter') ret.push(`${uids.get(uid)}님이 들어왔습니다.`)
        if (command === 'Leave') ret.push(`${uids.get(uid)}님이 나갔습니다.`)
    })

    return ret
}
profile
https://medium.com/@wooleejaan

0개의 댓글