본문 바로가기
코딩테스트(알고리즘)/프로그래머스

[프로그래머스] 크레인 인형뽑기 게임 (Javascript)

by Cafe Mocha 2022. 6. 23.

코딩테스트 연습 - 크레인 인형뽑기 게임 | 프로그래머스 (programmers.co.kr)

 

코딩테스트 연습 - 크레인 인형뽑기 게임

[[0,0,0,0,0],[0,0,1,0,3],[0,2,5,0,1],[4,2,4,4,2],[3,5,1,3,1]] [1,5,3,5,1,2,1,4] 4

programmers.co.kr


접근 : 스택

 

1. board를 newBoard로 변환(회전시킨후 0을 제거하고 reverse시켜서 pop()를 활용)

2. moves를 forEach로 돌면서 stk 값 확인

 

 Javascript

function solution(board, moves) {
    var answer = 0;
    let newBoard = [];
    let stk =[];
    //newBoard
    for(let i=0;i<board.length;i++){
        let temp =[];
        for(let j=0;j<board[0].length;j++){
            if(board[j][i]!==0) temp.push(board[j][i]);
        }
        newBoard.push(temp.reverse());
        temp =[];
    }
    console.log(newBoard);
    
    //moves check
    moves.forEach(num=>{
        if(newBoard[num-1].length !==0){        
            let temp = newBoard[num-1].pop();
            if(stk.length === 0) stk.push(temp);
            else {
                if(stk[stk.length-1] === temp){
                    stk.pop();
                    answer+=2;
                } else{
                    stk.push(temp);
                }
            }
        }
    })
    
    
    return answer;
}