원본 문제 : https://programmers.co.kr/learn/courses/30/lessons/42889?language=kotlin
<첫번째>
class Solution {
fun solution(N: Int, stages: IntArray): IntArray {
var answer = IntArray(N)
val frequency: MutableMap<Int, Int> = mutableMapOf()
val failureRate: MutableMap<Int, Double> = mutableMapOf()
for ( stage in stages ) {
if ( frequency.containsKey(stage)) {
frequency[stage] = frequency.getValue(stage) + 1
}
else {
frequency[stage] = 1
}
}
var numberOfUsers = stages.size
for ( i in 1..N ) {
if ( frequency.containsKey(i) ) {
failureRate[i] = (frequency.getValue(i)/numberOfUsers.toDouble())
numberOfUsers -= frequency.getValue(i)
}
else {
failureRate[i] = 0.0
}
}
val list = failureRate.toList().sortedByDescending { (_, value) -> value }
for( i in 0 until N)
answer[i] = list[i].first
return answer
}
}
<두번째> 2020/06/05
class Solution {
data class Stage(val stageIndex: Int, val failureRate: Double)
fun solution(N: Int, stages: IntArray): IntArray {
val list = MutableList<Int>(N, {i -> 0})
val stageList = mutableListOf<Stage>()
var personsLeft: Int = stages.size
for (i in 0 until N) {
list[i] = stages.count { it == i + 1 }
}
list.forEachIndexed { index, value ->
val rate: Double = value.toDouble() / personsLeft
stageList.add( Stage(index + 1,
rate?.takeIf { !it.isNaN() }
?.let { it } ?: 0.0 )
)
personsLeft -= value
}
val result = IntArray(N) { it -> 0}
stageList.sortedByDescending { it.failureRate }
.forEachIndexed { index, value ->
result[index] = value.stageIndex
}
return result
}
}
'프로그래머스 > 코딩연습1' 카테고리의 다른 글
[프로그래머스] 체육복(42862)(Kotlin) (0) | 2020.01.16 |
---|---|
[프로그래머스] 기능개발(42586)(Kotlin) (0) | 2020.01.14 |
[프로그래머스] 프린터 (42587)(Kotlin) (0) | 2020.01.13 |
[프로그래머스] 다리를 지나는 트럭(42583)(Kotlin) (0) | 2020.01.13 |
[프로그래머스] 네트워크(java)(43162) (0) | 2019.06.11 |
댓글