Kotlin/코딩테스트

[프로그래머스] 달리기 경주 - kotlin

깨노비 2023. 4. 6. 23:23
728x90
반응형

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

class Solution {
    fun solution(players: Array<String>, callings: Array<String>): Array<String> {

        val rank: MutableMap<String, Int> =
            players.mapIndexed { i, player -> player to i }
                .toMap()
                .toMutableMap()

        for (calling in callings) {
            val index = rank[calling]!!
            val chgPlayer = players[index - 1]

            val temp = players[index]
            players[index] = players[index - 1]
            players[index - 1] = temp

            rank[calling] = rank[calling]!! - 1
            rank[chgPlayer] = rank[chgPlayer]!! + 1
        }

        return players
    }
}
728x90
반응형