[프로그래머스]크레인 인형뽑기 게임 (javascript/자바스크립트)

스카치·2023년 3월 25일
0
post-thumbnail

문제

풀이 1

function solution(board, moves) {
    let cart = []
    let count = 0 
    moves.map(loc => {
        let index = loc-1
        for (let v of board) {
            if (v[index] !==0) {
                if (v[index] === cart[cart.length-1]) { 
                    cart.pop()
                    count += 2
                } else {
                    cart.push(v[index])
                }
                v[index] = 0
                break
            }
        }
    })
    return count;
}

풀이 2

const transpose = matrix =>
    matrix.reduce(
        (result, row) => row.map((_, i) => [...(result[i] || []), row[i]]),
        []
    );

const solution = (board, moves) => {
    const stacks = transpose(board).map(row =>
        row.reverse().filter(el => el !== 0)
    );
    const basket = [];
    let result = 0;

    for (const move of moves) {
        const pop = stacks[move - 1].pop();
        if (!pop) continue;
        if (pop === basket[basket.length - 1]) {
            basket.pop();
            result += 2;
            continue;
        }
        basket.push(pop);
    }

    return result;
};

0개의 댓글