알고리즘/프로그래머스
프로그래머스 - 크레인 인형뽑기 게임(카카오)
송민준
2021. 1. 27. 04:18
programmers.co.kr/learn/courses/30/lessons/64061?language=java
코딩테스트 연습 - 크레인 인형뽑기 게임
[[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
2차원 배열을 뽑기상자라고 보고 뽑기를 실행한만큼 Stack에 담아서 위아래 두 인형이 같으면 터트리는 게임.
Stack을 선택한 이유는 뽑기결과가 계속해서 쌓인다는 점과 최상단의 값을 활용해야 해서임.
import java.util.Stack;
/**
* 4, (3, (1, 1), 3), 2, 4
* (4, (3, (1, 1), 3), (2, 2), 4)
*/
public class CraneDollDrawGame {
public static int solution(int[][] board, int[] moves) {
// 1. 그릇
int answer = 0;
Stack<Integer> stack = new Stack<>();
// 2.
// 뽑기 실행
for(int popIndex = 0; popIndex < moves.length; popIndex++) {
int pop = moves[popIndex]-1;
// 각 섹터별(열) 위에서부터(행) 탐색
for(int height = 0; height < board.length; height++) {
int target = board[height][pop];
if(target == 0) {
continue;
}
// 0이 아니면 뽑았다고 봄
board[height][pop] = 0;
// 장바구니의 최상단이 뽑은거랑 같으면 pop, count++2
if(!stack.isEmpty() && target == stack.peek()) {
stack.pop();
answer+= 2;
break;
}
// 다르면 계속 push
stack.push(target);
break;
}
}
return answer;
}
}
다른 사람들의 풀이를 보니 나의 풀이와 비슷하긴 한데 stack에 push, pop 하는 부분만 조건문 순서가 조금 달랐던 것 같다.
ArrayList로 담아서 마지막에 for문 돌려서 앞뒤 같으면 삭제하던 풀이도 있고...
아래는 테스트 케이스다. 주어진 케이스보다 하나 더 해봤다.
import org.junit.Test;
import static org.junit.Assert.*;
public class CraneDollDrawGameTest {
@Test
public void solution() {
//given
int[][] board = {{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}};
int[] moves = {1, 5, 3, 5, 1, 2, 1, 4};
//when
int solution = CraneDollDrawGame.solution(board, moves);
//then
assertEquals(4, solution);
}
@Test
public void solution2() throws Exception {
//given
int[][] board = {{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}};
int[] moves = {1, 5, 3, 5, 1, 2, 2, 1, 4};
//when
int solution = CraneDollDrawGame.solution(board, moves);
//then
assertEquals(8, solution);
}
}