프린터

Falcon·2021년 1월 12일
1

programmers

목록 보기
3/27

문제

🔑풀이

import java.util.*

class Solution {
    fun solution(priorities: IntArray, location: Int): Int {
        val targetPriority = priorities[location]
        val circularQueue = Array<Pair<Int, Boolean>>(priorities.size){index-> Pair(priorities[index], false)}.toList() as ArrayList<Pair<Int, Boolean>>
//        Pair is data class so , we should copy() method for changing the value
        circularQueue[location] = circularQueue[location].copy(second = true)
        var answer = 0
        var headPair : Pair<Int, Boolean>
//        1round higher priority remove
        do {
            val moveCount : Int = with(circularQueue){
                map{it.first}.indexOf(maxOf { it.first })
            }
            with (circularQueue) {
                Collections.rotate(this, -moveCount)
                headPair = first()
                removeAt(0)
            }
            answer++
        } while (headPair.first > targetPriority)
        circularQueue.add(0, headPair)
        answer--

        // 2round , same priority
        for (index in circularQueue.indices) {
            if(circularQueue[index].first == targetPriority) answer++
            if(circularQueue[index].second) break
        }
        return answer
    }
}

🔨풀이 리펙토링

import java.util.*

class Solution {
    data class WorkPair(val priority: Int, val isTarget: Boolean) : Comparable<WorkPair>{
        override fun compareTo(nextWork: WorkPair) = this.priority.compareTo(nextWork.priority)
    }

    fun solution(priorities: IntArray, location: Int): Int {
        var answer = 1
        // 딜레마: queue 가 되는 순간 Collections.rotate 불가능 (List 형태여야함)
        // List 로 하면 first 를 뽑아서 일일히 확인하고 지워야함 (poll 없음..)

        val queue : ArrayList<WorkPair> = Array<WorkPair>(priorities.size){ index-> WorkPair(priorities[index], false)}.also { it[location] = it[location].copy(isTarget = true)}.toList() as ArrayList<WorkPair>
        while(true) {
            with(queue) {
                // 무조건 가장 큰 일까지 거리만큼 회전시킴
                Collections.rotate(this, -indexOf(maxOf{it}))
            }
            // 현재 첫번째 자리는 가장 우선순위 높은놈임, 이놈이 구하고자 하는 work 면 break
            if (!queue.first().isTarget) {
                queue.removeAt(0)
                answer++
            } else {
                break
            }
        }
        return answer
    }
}
profile
I'm still hungry

0개의 댓글