본문 바로가기
프로그래머스/코딩연습1

[프로그래머스] 실패율 (42889)(Kotlin)

by 유줘니 2020. 1. 14.

원본 문제 : 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
  }
}

댓글