본문 바로가기
front/js

[프로그래머스, 자바스크립트] 햄버거만들기

by juniKang 2022. 10. 30.

문제이해

 빨간 부분을 잘봐야한다. 6번째 재료가 쌓였을때, [ 3, 4, 5, 6]번 째 재료가 1, 2, 3, 1 인지 검사하고, 9번 째 재료가 쌓엿을 때, 마지막에서 4개의 재료가 1, 2, 3, 1 인지 검사해야 한다. 

 

 

 

[1, 1, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1]

 

위 케이스가 3개의 버거가 만들어져야 한다.

 

 

문제 이해를 잘 못하면 2개의 버거가 만들어진다.

 

 

 

사이드 이펙트가 없도록 makeBurger 함수를 만들었다. _arr은 makeBurger의 실행이 끝나면 가비지 컬렉터에 의해 메모리를 놓아줄 것으로 예상한다. 

function solution(ingredient) {

    const makeBurger = (array) => {
        const _arr = [];
        return array.reduce((total, aIngredient) => {
            _arr.push(aIngredient);
            if (_arr[_arr.length - 4] === 1 &&
                _arr[_arr.length - 3] === 2 &&
                _arr[_arr.length - 2] === 3 &&
                _arr[_arr.length - 1] === 1) {
                _arr.pop();
                _arr.pop();
                _arr.pop();
                _arr.pop();
                total++;
            }
            return total
        }, 0);
    }

    return makeBurger(ingredient);
}

실행중에 _arr이 (ingredient의 크기 - 만들어진 햄버거 크기*4) 만큼 메모리를 차지할 것 같은데, 아래코드로 적절히 _arr을 비워주면 메모리를 절약할 수 있겠지만 성능상에 별 차이없고 가독성도 해칠것 같아서 위의 코드를 그냥 쓸것같다.

function solution(ingredient) {
    let result = 0;
    let arr = [];
    let lastElement = null;

    const makeBurger = () => {
        if (arr.length > 3 &&
            arr[arr.length - 4] === 1 &&
            arr[arr.length - 3] === 2 &&
            arr[arr.length - 2] === 3 &&
            arr[arr.length - 1] === 1) {
            arr.pop()
            arr.pop()
            arr.pop()
            arr.pop()
            result++;
        }
    }
    const push = (aIngredient) => {
        switch (aIngredient) {
            case 1:
                arr.push(1);
                break;
            case 2:
                if (lastElement === 2 ||
                    lastElement === 3) {
                    arr = [];
                } else {
                    arr.push(2);
                }
                break;
            case 3:
                if (lastElement === 3) {
                    arr = [];
                } else {
                    arr.push(3);
                }
                break;
        }
        lastElement = aIngredient;
        makeBurger();
    };

    ingredient.forEach(push)

    return result;
}

댓글