링크 : https://school.programmers.co.kr/learn/courses/30/lessons/42583
import java.util.*;
class Solution {
public int solution(int bridge_length, int weight, int[] truck_weights) {
int answer = 0;
//큐 생성
List<Truck> waits = new ArrayList<>();
List<Truck> onBridge = new ArrayList<>();
//초기값 세팅
for(int i=0; i< truck_weights.length; i++){
//인덱스, 무게, 다리길이(진행상황)
waits.add(new Truck(i, truck_weights[i], bridge_length));
}
//두 배열 모두 사이즈가0이 아니면 참
while(!(onBridge.isEmpty() && waits.isEmpty())){
//다리위의 모든 트럭 순회
Iterator<Truck> bIt = onBridge.iterator();
while(bIt.hasNext()){
Truck next = bIt.next();
next.move();
if(next.checkFinish()) bIt.remove();
}
//대기 트럭 1개 접근
Iterator<Truck> wIt = waits.iterator();
if(wIt.hasNext()){
int sum = onBridge.stream().mapToInt(v -> v.weight).sum();
Truck next = wIt.next();
if(sum+next.weight <= weight){
onBridge.add(next);
wIt.remove();
}
}
//진행시간
answer++;
}
return answer;
}
public class Truck{
int index;
int weight;
int bridgePosition;
public Truck(int index, int weight, int bridge_length){
this.index = index;
this.weight = weight;
this.bridgePosition = bridge_length;
}
public void move(){
if(bridgePosition > 0) bridgePosition--;
}
public boolean checkFinish(){
return bridgePosition == 0;
}
@Override
public String toString() {
return "Truck{" +
"index=" + index +
", weight=" + weight +
", bridgePosition=" + bridgePosition +
'}';
}
}
}
'교육 > 코테' 카테고리의 다른 글
[프로그래머스]JAVA 디스크 컨트롤러 -힙 (0) | 2022.07.07 |
---|---|
[프로그래머스]JAVA 주식가격 -스택/큐 (1) | 2022.07.06 |
[프로그래머스]JAVA 프린터 -스택/큐 (0) | 2022.07.06 |
[프로그래머스]JAVA 베스트앨범 -해시 (0) | 2022.07.06 |
[프로그래머스]JAVA 위장-해시 (0) | 2022.07.05 |