본문 바로가기

컴퓨터공부/Javascript

[프로그래머스] javacript 제 01 문제 달리기 경주

by Life & study 2023. 5. 14.
반응형

<프로그래머스 코딩테스트> javacript 제 01 문제 달리기 경주 

 

문제 설명

문제 설명
얀에서는 매년 달리기 경주가 열립니다. 해설진들은 선수들이 자기 바로 앞의 선수를 추월할 때 추월한 선수의 이름을 부릅니다. 예를 들어 1등부터 3등까지 "mumu", "soe", "poe" 선수들이 순서대로 달리고 있을 때, 해설진이 "soe"선수를 불렀다면 2등인 "soe" 선수가 1등인 "mumu" 선수를 추월했다는 것입니다. 즉 "soe" 선수가 1등, "mumu" 선수가 2등으로 바뀝니다.

선수들의 이름이 1등부터 현재 등수 순서대로 담긴 문자열 배열 players와 해설진이 부른 이름을 담은 문자열 배열 callings가 매개변수로 주어질 때, 경주가 끝났을 때 선수들의 이름을 1등부터 등수 순서대로 배열에 담아 return 하는 solution 함수를 완성해주세요.

제한사항
5 ≤ players의 길이 ≤ 50,000
players[i]는 i번째 선수의 이름을 의미합니다.
players의 원소들은 알파벳 소문자로만 이루어져 있습니다.
players에는 중복된 값이 들어가 있지 않습니다.
3 ≤ players[i]의 길이 ≤ 10
2 ≤ callings의 길이 ≤ 1,000,000
callings는 players의 원소들로만 이루어져 있습니다.
경주 진행중 1등인 선수의 이름은 불리지 않습니다.
입출력 예
players	callings	result
["mumu", "soe", "poe", "kai", "mine"]	["kai", "kai", "mine", "mine"]	["mumu", "kai", "mine", "soe", "poe"]
입출력 예 설명
입출력 예 #1

4등인 "kai" 선수가 2번 추월하여 2등이 되고 앞서 3등, 2등인 "poe", "soe" 선수는 4등, 3등이 됩니다. 5등인 "mine" 선수가 2번 추월하여 4등, 3등인 "poe", "soe" 선수가 5등, 4등이 되고 경주가 끝납니다. 1등부터 배열에 담으면 ["mumu", "kai", "mine", "soe", "poe"]이 됩니다.

 

문제풀이해답

function solution(players, callings) {
  // Create a hashmap to store the current position of each player
  const position = {};
  for (let i = 0; i < players.length; i++) {
    position[players[i]] = i;
  }

  // Iterate over the callings array and update the positions of the players
  for (let i = 0; i < callings.length; i++) {
    const currentPlayer = callings[i];
    const currentPosition = position[currentPlayer];
    const nextPosition = currentPosition - 1;
    if (nextPosition >= 0) {
      // Swap positions with the player in front
      const nextPlayer = players[nextPosition];
      players[nextPosition] = currentPlayer;
      players[currentPosition] = nextPlayer;
      // Update the position hashmap
      position[currentPlayer] = nextPosition;
      position[nextPlayer] = currentPosition;
    }
  }

  return players;
}

const players = ["mumu", "soe", "poe", "kai", "mine"];
const callings = ["kai", "kai", "mine", "mine"];

const result = solution(players, callings);
console.log(result); // Output: ["mumu", "kai", "mine", "soe", "poe"]

 

코드분석,

 const currentPlayer = callings[i];  이란 무엇인가?

 

예제코드,

const callings = ["Alice", "Bob", "Charlie"];
let i = 1; // Assume we're processing the second element (i.e. "Bob")

const currentPlayer = callings[i]; // Assign "Bob" to the variable currentPlayer

console.log(currentPlayer); // Output: "Bob"

이렇게 코드를 작성하면,

 

i = 1 니까, Bob이 출력되는것을 확인할수있었다.

 


이 코드는 callings 배열을 반복하고 callings 순서에 따라 플레이어의 위치를 ​​업데이트합니다. 다음은 코드가 수행하는 작업에 대한 단계별 설명입니다.


for 루프는 callings 배열의 각 요소를 반복하는 데 사용됩니다. 루프 변수 'i'는 현재 반복을 추적하는 데 사용됩니다.
현재 플레이어는 const currentPlayer = callings[i];를 사용하여 currentPlayer 변수에 할당됩니다. 이것은 게임에서 앞으로 나아가야 하는 플레이어가 될 것입니다.
const currentPosition = position[currentPlayer];를 사용하여 position 개체에서 현재 플레이어의 위치를 ​​검색합니다.
'const nextPosition = currentPosition - 1;'을 사용하여 현재 위치에서 1을 빼서 현재 플레이어보다 앞선 다음 플레이어의 위치를 ​​계산합니다.
다음 위치가 배열 범위 내에 있는지 확인하기 위해 'if' 문이 사용됩니다. 다음 위치가 0보다 크거나 같으면 현재 플레이어와 다음 플레이어의 위치가 바뀝니다.
players[nextPosition] = currentPlayer;를 사용하여 현재 플레이어를 다음 플레이어의 위치로 지정하고 players[currentPosition] = nextPlayer를 사용하여 현재 플레이어의 위치를 ​​다음 플레이어로 지정하여 플레이어의 위치를 ​​바꿉니다. ;.
position[currentPlayer] = nextPosition;을 설정하여 position 객체에서 현재 플레이어의 위치를 ​​업데이트합니다.
position[nextPlayer] = currentPosition;을 설정하여 position 객체에서 다음 플레이어의 위치도 업데이트됩니다.
callings 배열의 모든 요소가 처리될 때까지 루프는 다음 반복으로 계속됩니다.

다음은 위의 단계를 설명하는 데 도움이 되는 예제 코드 스니펫입니다.

 

const players = ["Alice", "Bob", "Charlie", "David", "Eve"];
const callings = ["Bob", "Charlie", "Eve"];

const position = {};
for (let i = 0; i < players.length; i++) {
  position[players[i]] = i;
}

for (let i = 0; i < callings.length; i++) {
  const currentPlayer = callings[i];
  const currentPosition = position[currentPlayer];
  const nextPosition = currentPosition - 1;
  if (nextPosition >= 0) {
    const nextPlayer = players[nextPosition];
    players[nextPosition] = currentPlayer;
    players[currentPosition] = nextPlayer;
    position[currentPlayer] = nextPosition;
    position[nextPlayer] = currentPosition;
  }
}

console.log(players); // Output: ["Alice", "Charlie", "Bob", "David", "Eve"]



이 예에서 players 배열에는 5명의 플레이어가 포함되고 callings 배열에는 3명의 플레이어가 포함됩니다. position 개체는 각 플레이어를 players 배열의 초기 위치에 매핑하기 위해 for 루프를 사용하여 생성됩니다.


'for' 루프는 'callings' 배열의 각 요소를 반복하고 위에서 설명한 단계를 수행하여 플레이어의 위치를 ​​업데이트합니다. 마지막 console.log 문은 업데이트된 players 배열을 출력하며 callings 순서에 따라 재정렬되었습니다.

반응형

댓글