Weekly Chanllenge 21년 08월 3주차

문제 링크

프로그래머스 위클리 테스트 21년 8월 3주차

블록 모양 추출

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
```


## 전체 정답코드

```javascript
const dx = [1, 0, -1, 0];
const dy = [0, 1, 0, -1];

const getBundle = (arr, x, y, value) => {
const bundle = [];
const _x = x;
const _y = y;
const recur = (x, y, value) => {
if (arr[x][y] !== value) return;

bundle.push([x - _x, y - _y]);

arr[x][y] = value ? 0 : 1;

for (let i = 0; i < 4; i++) {
const nx = x + dx[i];
const ny = y + dy[i];
if (
nx >= 0 &&
nx < arr.length &&
ny >= 0 &&
ny < arr.length &&
arr[nx][ny] === value
) {
recur(nx, ny, value);
}
}
};
recur(x, y, value);

return bundle.sort();
};

const findBundles = (arr, value) => {
const bundles = [];
for (let i = 0; i < arr.length; i++) {
for (let j = 0; j < arr.length; j++) {
if (arr[i][j] === value) {
bundles.push(getBundle(arr, i, j, value));
}
}
}
return bundles;
};

const getRotatedBunbles = bundle => {
const bundles = [bundle];
for (let i = 0; i < 3; i++) {
bundles.push(
bundles[bundles.length - 1].map(([x, y]) => [-y || 0, x]).sort()
);
}
return bundles;
};

const mediateBundle = bundle => {
const [row, col] = bundle.reduce(
(acc, cur) => [Math.min(acc[0], cur[0]), Math.min(acc[1], cur[1])],
[Number.MAX_SAFE_INTEGER, Number.MAX_SAFE_INTEGER]
);
return bundle
.map(([r, c]) => [row < 0 ? r - row : r, col < 0 ? c - col : c])
.sort();
};

function solution(game_board, table) {
const blockBundles = findBundles(table, 1)
.map(bundle => getRotatedBunbles(bundle))
.map(rotatedBundle => rotatedBundle.map(bundle => mediateBundle(bundle)))
.map(rotatedBundle => rotatedBundle.map(bundle => bundle.flat().join('')));

const blankBundles = findBundles(game_board, 0).map(bundle =>
mediateBundle(bundle).flat().join('')
);

let answer = 0;
blankBundles.forEach(bundle => {
for (let i = 0; i < blockBundles.length; i++) {
if (blockBundles[i].includes(bundle)) {
blockBundles.splice(i, 1);
answer += Math.floor(bundle.length / 2);
break;
}
}
});
return answer;
}