-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPG_Truck.js
43 lines (41 loc) ยท 1.38 KB
/
PG_Truck.js
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
32
33
34
35
36
37
38
39
40
41
42
43
/**
* @desc site : programmers
* @desc level: 2
* @desc url : https://programmers.co.kr/learn/courses/30/lessons/42583#
*/
function solution(bridge_length, weight, truck_weights) {
let answer = 0;
//๋ค๋ฆฌ ์ํ ํ ์ด๊ธฐํ
const bridgeQueue = new Array(bridge_length).fill(0);
//๋ชจ๋ ํธ๋ญ์ด ์ง๋๊ฐ ๋ ๊น์ง ๋ฐ๋ณต
while (bridgeQueue.length) {
const truckWeight = truck_weights[0];
bridgeQueue.shift();
const totalWeight = getTotalWeight(bridgeQueue);
if (truckWeight) {
//๊ฑด๋ ํธ๋ญ + ํ์ฌ ๊ฑด๋๋ ์ค์ธ ํธ๋ญ์ด ํ์ฉ์ค๋ ์ดํ์ผ ๋
if (totalWeight + truckWeight <= weight) {
bridgeQueue.push(truck_weights.shift());
} else {
//๋ง์ฝ ๋ชจ๋ ๊ฑด๋์ ๋์๋ ์์ธ๋ก ํ์ฉ
if (!getTotalWeight(bridgeQueue)) {
bridgeQueue.push(truck_weights.shift());
} else {
bridgeQueue.push(0);
}
}
}
answer++;
}
return answer;
}
/**
* @desc : ๋ฐฐ์ด ํฉ๊ณ ๊ตฌํ๊ธฐ(๋ค๋ฆฌ๋ฅผ ์ง๋๋ ํธ๋ญ์ ์ด ์ค๋)
*/
function getTotalWeight(array) {
if (array.length) {
const reducer = (previousValue, currentValue) => previousValue + currentValue;
const totalWeight = array.reduce(reducer);
return totalWeight;
}
}