[js]달리기 경주

Park Bumsoo·2023년 9월 24일
0

JS알고리즘

목록 보기
3/7

문제 : 달리기 경주
출처 : 프로그래머스

풀이

function solution(players, callings) {
    const newPlayerData = new Map();
    let newCallings = callings
    
    players.forEach((player, idx) => {
        newPlayerData.set(player, idx);
    })
    
    newCallings.forEach((calling) => {
        const targetIdx = newPlayerData.get(calling);
        const aheadTarget = players[targetIdx - 1];

        [players[targetIdx], players[targetIdx -1]] = [players[targetIdx -1], players[targetIdx]];
        
        newPlayerData.set(calling, newPlayerData.get(calling) - 1);
        newPlayerData.set(aheadTarget, newPlayerData.get(calling) + 1);
    })
    
    return players;
}

이번문제는 해설진이 호명한 이름에따라 달리는 주자의 순위가 변동 되며
최종적으로 변동된 순위로 플레이어의 배열을 반환해주는 문제입니다.

  1. hash map을 사용하여 플레이어의 이름과 해당idx를 셋팅해줬습니다.

  2. 이후 호명한 순서대로 forEach문 내부에서 callings배열 인자의 순서를 바꾼 후 hash mapset해주었습니다.

profile
프론트엔드 주니어 개발자(React, Next.js)

0개의 댓글