-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrotate2DArray.js
114 lines (97 loc) · 2.37 KB
/
rotate2DArray.js
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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
// 旋转输出 m x n 的二维数组。
function getNumberBetween(from, to) {
return Math.floor(Math.random() * (to - from)) + from;
}
function generate2DArray(m, n) {
const arr = [];
for (let i = 0; i < m; i++) {
const inner = [];
for (let j = 0; j < n; j++) {
inner.push(getNumberBetween(-20, 100));
}
arr.push(inner);
}
console.log(arr);
return arr;
}
function getItemOf2DArray(array, row, column) {
if (row >= array.length || column >= array[0].length) {
throw Error('Error: index is wrong when getting item from 2D-array');
}
return array[row][column];
}
function getRotateItemFrom2DArray(array) {
const res = [];
const allRowCount = array.length, allColumnCount = array[0].length;
// 常量
const direction = {
RIGHT: 0,
DOWN: 1,
LEFT: 2,
UP: 3
};
// 初始个数、初始方向、初始坐标、初始边界
let count = 0;
let currentDirection = direction.RIGHT;
const cursor = {
row: 0,
column: -1
};
const bound = {
topWall: -1,
bottomWall: allRowCount,
leftWall: -1,
rightWall: allColumnCount
};
while (count < allRowCount * allColumnCount) {
switch (currentDirection) {
case direction.RIGHT: {
if (cursor.column >= bound.rightWall - 1) {
currentDirection = direction.DOWN;
bound.topWall++;
continue;
}
cursor.column++;
break;
}
case direction.DOWN: {
if (cursor.row >= bound.bottomWall - 1) {
currentDirection = direction.LEFT;
bound.rightWall--;
continue;
}
cursor.row++;
break;
}
case direction.LEFT: {
if (cursor.column <= bound.leftWall + 1) {
currentDirection = direction.UP;
bound.bottomWall--;
continue;
}
cursor.column--;
break;
}
case direction.UP: {
if (cursor.row <= bound.topWall + 1) {
currentDirection = direction.RIGHT;
bound.leftWall++;
continue;
}
cursor.row--;
break;
}
default:
throw Error('Wrong direction!');
}
res.push(getItemOf2DArray(array, cursor.row, cursor.column));
count++;
}
return res;
}
function main() {
const arr = generate2DArray(7, 5);
const res = getRotateItemFrom2DArray(arr);
console.log(res.join(' '));
}
main();