Notice
Recent Posts
Recent Comments
Link
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
Tags
more
Archives
Today
Total
관리 메뉴

개발 일기장

[프로그래머스]스택/큐 - 트럭문제 본문

프로그래머스 코딩테스트

[프로그래머스]스택/큐 - 트럭문제

enow 2020. 7. 20. 00:10
package stackqueue;

import java.util.LinkedList;
import java.util.Stack;

public class TruckStreet {
	class Truck {
		int legnth;
		int weight;

		public Truck(int legnth, int weight) {
			this.legnth = legnth;
			this.weight = weight;
		}
		
	}

	public int solution(int bridge_length, int weight, int[] truck_weights) {
		int answer = 0;

		LinkedList<Truck> ing = new LinkedList<Truck>();
		Stack<Integer> wait = new Stack<Integer>();

		
		for (int j = truck_weights.length - 1; j >= 0; j--) {
			wait.push(truck_weights[j]);
		}

		while (true) {

			answer++;
			
			for (int h = 0; h < ing.size(); h++) {
				ing.get(h).legnth = ing.get(h).legnth + 1;
				if (ing.get(h).legnth == bridge_length) {
					ing.remove();
					h=h-1;
				}
			}

			
			int sum = 0;
			for (int h = 0; h < ing.size(); h++) {
				sum = sum + ing.get(h).weight;
			}

			if (!wait.isEmpty()) {
				if ((sum + wait.peek()) <= weight) {
					Truck t = new Truck(0, wait.pop());
					ing.add(t);
				}
			}

			/*
			 * System.out.println(answer + " " + wait + " " + ing.peekFirst().weight + " "+
			 * ing.peekLast().weight);
			 */
			if (ing.peekFirst() == null && wait.isEmpty() == true) {
				break;
			}
		}
		return answer;
	}

	public static void main(String[] args) {

		int bridge_length = 100;
		int weight = 100;
		int[] truck_weights = { 10,10,10,10,10,10,10,10,10,10 };

		TruckStreet st = new TruckStreet();

		System.out.print(st.solution(bridge_length, weight, truck_weights));

	}

}

굉장히 막혔던 부분은 이 부분이다.

for (int h = 0; h < ing.size(); h++) {
				ing.get(h).legnth = ing.get(h).legnth + 1;
				if (ing.get(h).legnth == bridge_length) {
					ing.remove();
					h=h-1;
				}
			}

굉장히 주의해야할점이다. LinkedList 자체가 가변길이다보니까 remove()하는 과정에서 index값이 변해버린다. 그래서 제대로된

반복문이 실행되지도않고 잘못하면 ConcurrentModificationException오류가 발생할수도 있다. 앞으로 이런부분이 있다면 굉장히 조심해야한다.

가변길이를 반복문돌릴때 한번더 생각해보는 습관을가지자

Comments