[Snow-ball]프로그래밍(컴퓨터)/Algorithm
[Algorithm] 달리기 경주 (JavaScript - Programmers)
Snow-ball
2023. 4. 11. 13:21
반응형
문제 설명
얀에서는 매년 달리기 경주가 열립니다. 해설진들은 선수들이 자기 바로 앞의 선수를 추월할 때 추월한 선수의 이름을 부릅니다. 예를 들어 1등부터 3등까지 "mumu", "soe", "poe" 선수들이 순서대로 달리고 있을 때, 해설진이 "soe"선수를 불렀다면 2등인 "soe" 선수가 1등인 "mumu" 선수를 추월했다는 것입니다. 즉 "soe"선수가 1등, "mumu" 선수가 2등으로 바뀝니다.
선수들의 이름이 1등부터 현재 등수 순서대로 담긴 문자열 배열 players 와 해설진이 부른 이름을 담은 문자열 배열 callings 가 매개변수로 주어질 때, 경주가 끝났을 때 선수들의 이름을 1등부터 등수 순서대로 배열에 담아 return 하는 solution 함수를 완성해주세요.
문제 풀이
1)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
function solution(players, callings) {
const map = new Map();
players.forEach((key, value) => map.set(key, value))
callings.forEach((el) => {
const index = map.get(el)
const moveIndex = index - 1;
const player = players[moveIndex];
players[moveIndex] = players[index];
players[index] = player;
map.set(el, moveIndex);
map.set(player, index);
})
return players;
}
|
cs |
2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
function solution(players, callings) {
const object = {};
players.forEach((key, value) => object[key] = value);
callings.forEach((el, inx) => {
const index = object[callings[inx]];
const player = players[index - 1];
players[index - 1] = players[index];
players[index] = player;
object[player]++
object[callings[inx]]--
})
return players;
}
|
cs |
반응형