본문 바로가기

프로그래머스 알고리즘 문제/Level 2

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

내 정답:

 

def solution(bridge_length, weight, truck_weights):
    def appendTruck(arr, truck_weight):
        arr.append([truck_weight, 0])
    bridge = []
    appendTruck(bridge, truck_weights.pop(0))
    t = 0
    wsum = 0
    while len(truck_weights) > 0 or len(bridge) > 0:
        t += 1
        for truck in bridge:
            truck[1] += 1
        for truck in bridge:
            if truck[1] > bridge_length:
                bridge.pop(0)
        if truck_weights and sum(truck[0] for truck in bridge if truck[1] != bridge_length) + truck_weights[0] <= weight:
            appendTruck(bridge, truck_weights.pop(0))
    return t

 

다른 사람들의 정답:

 

클래스 사용

import collections

DUMMY_TRUCK = 0


class Bridge(object):

    def __init__(self, length, weight):
        self._max_length = length
        self._max_weight = weight
        self._queue = collections.deque()
        self._current_weight = 0

    def push(self, truck):
        next_weight = self._current_weight + truck
        if next_weight <= self._max_weight and len(self._queue) < self._max_length:
            self._queue.append(truck)
            self._current_weight = next_weight
            return True
        else:
            return False

    def pop(self):
        item = self._queue.popleft()
        self._current_weight -= item
        return item

    def __len__(self):
        return len(self._queue)

    def __repr__(self):
        return 'Bridge({}/{} : [{}])'.format(self._current_weight, self._max_weight, list(self._queue))


def solution(bridge_length, weight, truck_weights):
    bridge = Bridge(bridge_length, weight)
    trucks = collections.deque(w for w in truck_weights)

    for _ in range(bridge_length):
        bridge.push(DUMMY_TRUCK)

    count = 0
    while trucks:
        bridge.pop()

        if bridge.push(trucks[0]):
            trucks.popleft()
        else:
            bridge.push(DUMMY_TRUCK)

        count += 1

    while bridge:
        bridge.pop()
        count += 1

    return count


def main():
    print(solution(2, 10, [7, 4, 5, 6]), 8)
    print(solution(100, 100, [10]), 101)
    print(solution(100, 100, [10, 10, 10, 10, 10, 10, 10, 10, 10, 10]), 110)


if __name__ == '__main__':
    main()

 

간단한 알고리즘 사용 (진짜 도로를 건너는 것처럼 하나씩 땡겨온다)

def solution(bridge_length, weight, truck_weights):
    q=[0]*bridge_length
    sec=0
    while q:
        sec+=1
        q.pop(0)
        if truck_weights:
            if sum(q)+truck_weights[0]<=weight:
                q.append(truck_weights.pop(0))
            else:
                q.append(0)
    return sec