-
https://programmers.co.kr/learn/challenges
내 풀이
function solution(record) { var answer = []; let splitRecord = new Map(); // 특정 id의 행동 let nickChange = new Map(); // 특정 id의 nickname let decompose = []; // record 쪼개기 for (let i = 0; i < record.length; i++) { let getInfo = record[i].split(' '); decompose.push(getInfo); } for (let i = 0; i < record.length; i++) { let action = decompose[i][0]; let id = decompose[i][1]; let nick = decompose[i][2]; let info = nick ? [action, nick] : [action]; if (splitRecord.has(id)) { let getInfo = splitRecord.get(id); getInfo.push(info); splitRecord.set(id, getInfo); } else { splitRecord.set(id, [info]); } } for (let id of splitRecord.keys()) { let getInfo = splitRecord.get(id); let len = getInfo.length - 1; while (len >= 0) { if (getInfo[len][1]) { // 특정 id의 마지막 닉네임 저장 nickChange.set(id, getInfo[len][1]); break; } len--; } } for (let i = 0; i < decompose.length; i++) { let id = decompose[i][1]; // id 추출 let modifyNick = nickChange.get(id); // id의 닉네임 검출 let action = decompose[i][0].charCodeAt([0]); // id의 action 검출 switch (action) { case 69: // Enter answer.push(modifyNick + "님이 들어왔습니다."); break; case 76: // Leave answer.push(modifyNick + "님이 나갔습니다."); break; default: break; } } // console.log(decompose) // console.log(nickChange) // console.log(splitRecord); return answer; }
닉네임이 수정되면 덮어쓰기된다. 풀이를 개선하면,
function solution(record) { var answer = []; let splitRecord = new Map(); // 특정 id의 행동 let nickChange = new Map(); // 특정 id의 nickname let decompose = []; // record 쪼개기 for (let i = 0; i < record.length; i++) { let getInfo = record[i].split(' '); decompose.push(getInfo); } for (let i = 0; i < record.length; i++) { let action = decompose[i][0]; let id = decompose[i][1]; let nick = decompose[i][2]; if(nick) { info = [action, nick]; nickChange.set(id, nick); } else { info = [action]; } if (splitRecord.has(id)) { let getInfo = splitRecord.get(id); getInfo.push(info); splitRecord.set(id, getInfo); } else { splitRecord.set(id, [info]); } } // for (let id of splitRecord.keys()) { // let getInfo = splitRecord.get(id); // let len = getInfo.length - 1; // while (len >= 0) { // if (getInfo[len][1]) { // 특정 id의 마지막 닉네임 저장 // nickChange.set(id, getInfo[len][1]); // break; // } // len--; // } // } for (let i = 0; i < decompose.length; i++) { let id = decompose[i][1]; // id 추출 let modifyNick = nickChange.get(id); // id의 닉네임 검출 let action = decompose[i][0].charCodeAt([0]); // id의 action 검출 switch (action) { case 69: // Enter answer.push(modifyNick + "님이 들어왔습니다."); break; case 76: // Leave answer.push(modifyNick + "님이 나갔습니다."); break; default: break; } } // console.log(decompose) // console.log(nickChange) // console.log(splitRecord); return answer; }
'알고리즘 > 프로그래머스' 카테고리의 다른 글
[Lv2] 배달 (0) 2021.06.26 [Lv2] 124 나라 숫자 (0) 2021.06.21 [Lv3] 입국심사 (0) 2021.06.16 [Lv2] 멀쩡한 사각형 (0) 2021.06.14 [Lv3] 네트워크 (0) 2021.05.26 댓글