Skip to content

Commit 3649725

Browse files
committed
Add: algorithm of programmers
1 parent 3c36aa7 commit 3649725

File tree

2 files changed

+63
-0
lines changed

2 files changed

+63
-0
lines changed
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
package io.github.imsejin.study.programmers.lv1;
2+
3+
import java.util.ArrayDeque;
4+
import java.util.Deque;
5+
import java.util.Objects;
6+
7+
/**
8+
* <a href="https://school.programmers.co.kr/learn/courses/30/lessons/64061">크레인 인형뽑기 게임</a>
9+
*/
10+
public class L64061 {
11+
12+
static int solve(int[][] board, int[] moves) {
13+
int count = 0;
14+
Deque<Integer> stack = new ArrayDeque<>();
15+
16+
for (int move : moves) {
17+
int[] row = board[move - 1];
18+
for (int i = 0; i < row.length; i++) {
19+
int cell = board[i][move - 1];
20+
21+
if (cell > 0) {
22+
Integer prev = null;
23+
if (!stack.isEmpty()) {
24+
prev = stack.peekLast();
25+
}
26+
27+
stack.offerLast(cell);
28+
board[i][move - 1] = 0;
29+
30+
if (Objects.equals(prev, cell)) {
31+
stack.pollLast();
32+
stack.pollLast();
33+
count++;
34+
}
35+
36+
break;
37+
}
38+
}
39+
}
40+
41+
return count * 2;
42+
}
43+
44+
}
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
package io.github.imsejin.study.programmers.lv1
2+
3+
import spock.lang.Specification
4+
5+
class L64061Spec extends Specification {
6+
7+
def "test"() {
8+
when:
9+
def actual = L64061.solve(board as int[][], moves as int[])
10+
11+
then:
12+
actual == expected
13+
14+
where:
15+
board | moves || expected
16+
[[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
17+
}
18+
19+
}

0 commit comments

Comments
 (0)