프로그래머스 Lv.1 크레인인형뽑기

Kim Jason·2023년 4월 3일
0

알고리즘 노트

목록 보기
25/35
post-thumbnail

💁🏻 코드

function pickDoll(board, order) {
    for (let i = 0; i < board.length; i++) {
    	// ✅ 뽑힌 인형이 있다면
        if (!!board[i][order]) {
            let target = board[i][order];
            board[i][order] = 0;
            return target;
        }
    }
}

function solution(board, moves) {
    const stack = [];
    let answer = 0;
    
    moves.forEach(el => {
        const pickedDoll = pickDoll(board, el - 1);
        // ✅ 뽑힌 인형이 있다면
        if (pickedDoll) {
            // ✅ 이전 인형과 뽑힌 인형이 같은 경우
            if (stack[stack.length - 1] === pickedDoll) {
                stack.pop();
                answer += 2;
            } else {
                // ✅ 이전 인형과 뽑힌 인형이 같지 않은 경우
                stack.push(pickedDoll);
            }
        }
    });
    
    return answer;
}

입력값의 제한은 다음과 같다.

  • 5 <= board 한 변의 길이 <= 30
  • 1 <= moves 배열 <= 1,000

어떤 알고리즘을 사용해도 무방하다고 생각했다.
배열 board은 2 by 2 행렬의 형태다.
그렇기 때문에 pickDoll 함수를 새로 생성해서 중첩된 배열을 하나씩 살펴보면서 특정 행의 특정 열(order)이 0이 아닌 경우를 찾는다.

profile
성장지향형 프론트엔드 개발자

0개의 댓글