-
Notifications
You must be signed in to change notification settings - Fork 1
/
matrix.js
53 lines (39 loc) · 1.04 KB
/
matrix.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
function matrix(num) {
let matrixArr = [];
for (let k = 0; k < num; k++) {
matrixArr.push([])
}
let startRow = 0,
startColumn = 0;
let endRow = num - 1,
endColumn = num - 1;
let counter = 1;
while (startRow <= endRow && startColumn <= endColumn) {
// top row
for (let k = startColumn; k <= endColumn; k++) {
matrixArr[startRow][k] = counter;
counter++;
}
startRow++;
// right column
for (let k = startRow; k <= endRow; k++) {
matrixArr[k][endColumn] = counter;
counter++;
}
endColumn--;
// bottom row
for (let k = endColumn; k >= startColumn; k--) {
matrixArr[endRow][k] = counter;
counter++;
}
endRow--;
// left column
for (let k = endRow; k >= startRow; k--) {
matrixArr[k][startColumn] = counter;
counter++;
}
startColumn++;
}
console.log(matrixArr);
}
matrix(3)