프로그래머스/Lv.1
프로그래머스 JS [달리기 경주]
sakuraop
2023. 5. 8. 19:13
https://school.programmers.co.kr/learn/courses/30/lessons/178871
문제 요약
자기 바로 앞의 선수를 추월할 때 추월한 선수의 이름을 부릅니다
해설진이 "soe"선수를 불렀다면 2등인 "soe" 선수가 1등인 "mumu" 선수를 추월했다는 것
풀이 :
초기 players의 인덱스를 생성
추월한 선수의 index-1
추월당한 선수의 index+1
function solution(players, callings) {
const playerObject = {}
const playerIndex = players.map((player,index) => {
playerObject[player] = index
return [player,index]
})
for (const call of callings) {
// 추월하기 전의 상태를 저장
const forward = playerIndex[playerObject[call]-1]
const behind = playerIndex[playerObject[call]]
// 추월한 뒤의 상태로 업데이트
playerIndex[playerObject[call]-1] = behind
playerIndex[playerObject[call]] = forward
playerObject[forward[0]] += 1
playerObject[behind[0]] -= 1
}
// 결과를 정렬한 뒤 이름 배열을 반환
const sortedPlayers = Object.entries(playerObject).sort((a,b) => a[1]-b[1])
return sortedPlayers.map(playerIndex => playerIndex[0])
}