fffo

[코테뿌수기] 스텍/큐 본문

Programming/Algorithm

[코테뿌수기] 스텍/큐

gggs 2022. 2. 8. 22:24

연습

기능개발

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

function solution(progresses, speeds) {
    const result = [];
    let day = 1;
    progresses.forEach((progress, i) => {
        if (100 <= progress + (speeds[i] * day)) {
            result[result.length - 1]++;
            return ;
        }
        while (progress + (speeds[i] * day) < 100) {
            day++;
        }
        result.push(1);
    });
    return result;
}

프린터

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

function solution(priorities, location) {
    const documents = priorities.map((priority, index) => ({priority, index}));
    let count = 0;
    while (count < priorities.length) {
        const toPrint = documents.shift();
        if (documents.some(doc => toPrint.priority < doc.priority))
            documents.push(toPrint);
        else if (toPrint.index === location)
            return (count + 1);
        else
            count++;
    }
}

다리를 지나는 트럭

function solution(bridge_length, weight, truck_weights) {
  let bridge_queue = [];
  let cur_bridge_weight = 0;
  let time = 0;
  let cur_truck_weight = truck_weights.shift();
  while (cur_truck_weight) {
    bridge_queue.unshift(0);
    if (bridge_queue.length > bridge_length) {
      cur_bridge_weight -= bridge_queue.pop();
    }
    if (cur_bridge_weight + cur_truck_weight <= weight) {
      bridge_queue[0] = cur_truck_weight;
      cur_bridge_weight += cur_truck_weight;
      cur_truck_weight = truck_weights.shift();
    }
    time++;
  }
  time += bridge_length;
  return time;
}

아래는 위와 같은 로직에서 객체의 프로퍼티 키를 활용해 가독성을 높이려는 시도. 뭐가 더 좋은지는 아직 모르겠음

function solution(bridge_length, weight, truck_weights) {
    const weightArr = truck_weights.slice();
    const onBridge = [];
    let time = 0;
    while (weightArr.length || onBridge.length) {
        const curWeight = weightArr.shift();
        if (!curWeight)
            return onBridge[0].timeToPass;
        if (onBridge.length && onBridge[onBridge.length - 1].timeToPass === time)
            onBridge.pop();
        while (weight < curWeight + onBridge.reduce((total, {truckWeight}) => total + truckWeight, 0))
            time = onBridge.pop().timeToPass - 1;
        onBridge.unshift({"truckWeight" : curWeight, "timeToPass" : time + bridge_length + 1});
        time++;
    }
    return time;
}

'Programming > Algorithm' 카테고리의 다른 글

[코테뿌수기] 정렬  (0) 2022.02.07
[코테뿌수기] hash  (0) 2022.02.06
[js문제풀이] 경주로 건설  (0) 2021.11.05
[js문제풀이] 표 편집  (0) 2021.11.04
[js문제풀이] 광고 삽입  (0) 2021.11.01
Comments