Jordi, a game developer, wants to make a crane puppet machine into a mobile game.
In order to increase the fun of the game, Jordi tries to reflect the screen composition and rules in the game logic as follows.
The game screen is an N x N square grid of 1 x 1 squares with a crane on the top and a basket on the right. (The picture above is an example of a 5 x 5 size). Each grid cell contains a variety of puppets, and a cell without puppets is blank. All dolls occupy one 1 x 1 grid and are stacked one after the other, starting from the bottom of the grid. The game user can move the crane left and right to pick up the topmost doll from the stopped position. The dolls you pick up are stacked in a basket, and the dolls are stacked in order from the bottom of the basket. The following figure shows how the dolls are picked up in order from the positions [No. 1, No. 5, and No. 3] and placed in the basket.
If two dolls of the same shape are stacked consecutively in a basket, they will explode and disappear from the basket. In the above situation, if you pick up dolls from [No. 5] and stack them in the basket, two dolls of the same shape will disappear.
There is no case that the doll is not picked up when the crane is operated, but nothing happens if the crane is operated in a place where there is no doll. It also assumes that the basket is large enough to fit all the dolls. (In the figure, it is expressed with only 5 spaces due to screen display restrictions)
When the two-dimensional array board containing the grid state of the game screen and the array moves containing the position where the crane was operated to pick up the puppets are given as parameters, a solution function to return the number of puppets that are popped and disappeared after all the cranes are operated please complete.
[
[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],
]; //board 배열
[1, 5, 3, 5, 1, 2, 1, 4]; //moves 배열
4
function solution(board, moves) {
let answer = 0,
stack = [],
i = 0;
while (i < moves.length) {
const pos = parseInt(moves[i]) - 1;
for (let j in board) {
if (board[j][pos]) {
if (stack[stack.length - 1] === board[j][pos]) {
stack.pop();
board[j][pos] = 0;
answer += 2;
i++;
} else if (j >= board.length - 1) i++;
else {
stack.push(board[j][pos]);
board[j][pos] = 0;
}
}
}
}
return answer;
}
break
function solution(board, moves) {
let answer = 0,
stack = [];
moves.forEach((pos) => {
for (let i = 0; i < board.length; i++) {
if (board[i][pos - 1] !== 0) {
let tmp = board[i][pos - 1];
board[i][pos - 1] = 0;
if (tmp === stack[stack.length - 1]) {
stack.pop();
answer += 2;
} else stack.push(tmp);
break;
}
}
});
return answer;
}