forked from JackPu/JavaScript-Algorithm-Learning
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathqipan.js
More file actions
102 lines (89 loc) · 2.98 KB
/
qipan.js
File metadata and controls
102 lines (89 loc) · 2.98 KB
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
94
95
96
97
98
99
100
/**
假设我们现在有一个 3 x 3 的井字棋游戏,我们用一个二维数组代表棋盘,’x’ 代表玩家 X 下的棋子,’o’ 代表玩家 O 下的棋子,’e’ 代表该格没有棋子。例如:
一个空白的棋盘以下面的二维数组表示
[ [‘e’, ‘e’, ‘e’],
[‘e’, ‘e’, ‘e’],
[‘e’, ‘e’, ‘e’] ]
如果玩家 X 在第一行第一列下了一步棋,玩家 O 在第二行第二列下了一步棋,则表示如下:
[ [‘x’, ‘e’, ‘e’],
[‘e’, ‘o’, ‘e’],
[‘e’, ‘e’, ‘e’] ]
现在需要一个 function,接受一个已有任意棋子的棋盘(和上面二维数组一样的格式),和玩家的标志(’x’ 或 ‘o'),返回该玩家下一步有几种可能的获胜方式(获胜方式以数组表示,[0, 0] 代表在第一行第一列下一步棋即可获胜,[2, 2] 代表在第三行第三列下一步棋即可获胜)。例如:
someFunction(
‘x’,
[ [‘o’, ‘e’, ‘e’],
[‘o’, ‘x’, ‘o’],
[‘x’, ‘x’, ‘e’] ]
)
// return [ [2, 2], [0, 1], [0, 2] ]
someFunction(
‘x’,
[ [‘x’, ‘o’, ‘o’],
[‘x’, ‘x’, ‘e’],
[‘e’, ‘o’, ‘e’] ]
)
// return [ [2, 2], [1, 2], [2, 0] ]
someFunction(
‘x’,
[ [‘x’, ‘x’, ‘o’],
[‘e’, ‘e’, ‘e’],
[‘e’, ‘e’, ‘e’] ]
)
// return [ ]
someFunction(
‘o’,
[ [‘o’, ‘o’, ‘o’],
[‘e’, ‘e’, ‘e’],
[‘e’, ‘e’, ‘e’] ]
)
return [ ]
*/
// find 'e' to check the empty coordinates
const findE = function (arr) {
const eCoor = [];
arr.forEach((row, i) => {
row.forEach((val, j) => {
if (val === 'e') {
eCoor.push([i, j])
}
});
})
return eCoor;
}
const checkVictory = function(x, y, role, arr, degree) {
arr[x][y] = role;
let result = false;
if (degree === 0) {
result = arr[x][0] === role && arr[x][1] === role && arr[x][2] === role;
} else if (degree === 90) {
result = arr[0][y] === role && arr[1][y] === role && arr[2][y] === role;
} else if (degree === 45) {
result = arr[0][0] === role && arr[1][1] === role && arr[2][2] === role;
} else if (degree === -45) {
result = arr[0][2] === role && arr[1][1] === role && arr[2][0] === role;
}
arr[x][y] = 'e';
return result;
}
// check if win to select the coordinate
const queryVictory = function (role, coors, arr) {
const victoryResults = [];
coors.forEach((item) => {
var x = item[0];
var y = item[1];
[-45, 0, 45, 90].forEach((degree) => {
if (checkVictory(x, y, role, arr, degree)) {
return victoryResults.push([x, y]);
}
})
});
return victoryResults;
}
module.exports = function getResult(role, arr) {
const result = [];
const eCoor = findE(arr);
if (eCoor.length === 0) {
return [];
}
return queryVictory(role, eCoor, arr);
}