[프로그래머스 lev2/JS] 다리를 지나는 트럭

woolee의 기록보관소·2022년 11월 21일
0

알고리즘 문제풀이

목록 보기
102/178

문제 출처

프로그래머스 lev2 - 다리를 지나는 트럭

나의 풀이

1차 시도 (실패)

시간이 흘러가는 기준이 다리 길이라는 점을 생각하지 못했다.

function solution(bl, w, tw) {
  let time = 0;
  let crossed = [];
  let crossing = [];

  while(tw.length) {
    let sum = crossing.reduce((a,b) => a+b,0);

    if (crossing.length <= bl-1 && (sum+tw[0]) <= w) {
      crossing.push(tw.shift());
      time += 1;
    } else {
      crossed.push(crossing.shift());
      crossing.push(tw.shift());
      time += 2;
    }
  }
  return time + bl;
}

// console.log(solution(2, 10, [7, 4, 5, 6]));
// console.log(solution(100, 100, [10]));
console.log(solution(100, 100, [10, 10, 10, 10, 10, 10, 10, 10, 10, 10]));

2차 시도 (통과)

다리 길이만큼 while문을 돌아서 풀었다. 하지만 다리 길이만큼 while문을 돌면, 다리가 한없이 길어질 때 문제가 생기지 않을까

function solution(bl, w, tw) {
  let time = 0;
  let bridge = Array.from({length: bl}, () => 0);
  let tsum = 0;

  time++;
  bridge.shift();
  tsum += tw[0];
  bridge.push(tw.shift());

  while (tsum) {
    time++;
    tsum -= bridge.shift();

    if (tw.length > 0 && tsum + tw[0] <= w) {
      tsum += tw[0];
      bridge.push(tw.shift());
    } else {
      bridge.push(0);
    }
  }
  return time;
}

console.log(solution(2, 10, [7, 4, 5, 6]));
console.log(solution(100, 100, [10]));
console.log(solution(100, 100, [10, 10, 10, 10, 10, 10, 10, 10, 10, 10]));

다른 풀이

시간을 일일이 순회하지 않고, 남은 시간을 더해주는 방식

function solution(bridge_length, weight, truck_weights) {
  
  let time = 0, qu = [[0, 0]], weightOnBridge = 0;

  while (qu.length > 0 || truck_weights.length > 0) {

    if (qu[0][1] === time) weightOnBridge -= qu.shift()[0];

    if (weightOnBridge + truck_weights[0] <= weight) {
      weightOnBridge += truck_weights[0];
      qu.push([truck_weights.shift(), time + bridge_length]);
    } else {
      if (qu[0]) time = qu[0][1] - 1;
    }
    time++;
  }
  return time;
}
profile
https://medium.com/@wooleejaan

0개의 댓글