프로그래머스/코딩연습1
[프로그래머스] 다리를 지나는 트럭(42583)(Kotlin)
유줘니
2020. 1. 13. 12:17
원본 문제 : https://programmers.co.kr/learn/courses/30/lessons/42583
<첫번째> 2020/01/13
import java.util.*
class Solution {
fun solution(bridge_length: Int, weight: Int, truck_weights: IntArray): Int {
var answer = 0
val truckQueue: Queue<Int> = LinkedList<Int>(truck_weights.toList())
val bridgeQueue: Queue<Int> = LinkedList<Int>()
val bridgeProgessQueue: Queue<Int> = LinkedList<Int>()
bridgeQueue.add(truckQueue.poll())
bridgeProgessQueue.add(bridge_length)
answer++
while(!bridgeQueue.isEmpty() && !truck_weights.isEmpty()) {
answer++
// println("Count: $answer\tTruckQueue: $truckQueue \tBridgeQueue: $bridgeQueue")
val progressSize = bridgeProgessQueue.size
if(bridgeProgessQueue.size != 0) {
for (progress in 0 until progressSize) {
bridgeProgessQueue.add(bridgeProgessQueue.poll() - 1)
}
}
if (bridgeProgessQueue.peek() == 0) {
bridgeProgessQueue.poll()
bridgeQueue.poll()
}
// println("Bridge Progress: $bridgeProgessQueue")
var bridgeWeights = 0
for(trucks in bridgeQueue) {
if (trucks != null)
bridgeWeights += trucks
}
if(!truckQueue.isEmpty() && bridgeWeights + truckQueue.peek() <= weight) {
bridgeQueue.add(truckQueue.poll())
bridgeProgessQueue.add(bridge_length)
}
}
return answer
}
}
<두번째> 성공 2020/06/04
import java.util.*
data class Truck(val weight: Int, var count: Int)
class Solution {
fun solution(bridge_length: Int, weight: Int, truck_weights: IntArray): Int {
val bridgeQueue: LinkedList<Truck> = LinkedList<Truck>()
val truckQueue: LinkedList<Truck> = LinkedList<Truck>()
for (truck in truck_weights)
truckQueue.add(Truck(truck, bridge_length))
var answer: Int = 0
while (!bridgeQueue.isEmpty() || !truckQueue.isEmpty()) {
answer++
if (!bridgeQueue.isEmpty() && bridgeQueue.peekFirst().count < 2)
bridgeQueue.poll()
if (!bridgeQueue.isEmpty())
bridgeQueue
.forEach { it.count -= 1 }
if (!truckQueue.isEmpty() && bridgeQueue.sumBy { it.weight } + truckQueue.peek().weight <= weight)
bridgeQueue.add(truckQueue.poll())
}
return answer
}
}