https://school.programmers.co.kr/learn/courses/30/lessons/42583?language=javascript 

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

function solution(bridge_length, weight, truck_weights) {
    const bridge = new Array(bridge_length).fill().map((v) => 0);
    
    let time = 0;
    let bridge_weight = 0
    let truck_number = truck_weights.length;
    
    while(truck_number > 0) {
        // console.log(bridge, time);
        time++;
        bridge_weight = bridge.reduce((partialSum, a) => partialSum + a, 0);
        if(bridge_weight <= weight
           && bridge_weight + truck_weights[0] <= weight) {
            let b = bridge.shift();
            if(b > 0) truck_number--;
            bridge.push(truck_weights.shift());
        } else if(bridge_weight <= weight 
                 && bridge_weight + truck_weights[0] > weight) {
            let b = bridge.shift();
            if(b > 0) truck_number--;
            bridge_weight = bridge.reduce((partialSum, a) => partialSum + a, 0);
            if(bridge_weight <= weight 
                 && bridge_weight + truck_weights[0] <= weight) {
                bridge.push(truck_weights.shift());
            } else bridge.push(0);
        } else if(bridge_weight <= weight && truck_weights.length === 0){
            let b = bridge.shift();
            if(b > 0) truck_number--;
            bridge.push(0);
        }
    }
        
    return time;
}

코드가 많이 지저분하다..

728x90

+ Recent posts