1
var generateMatrix = function (n) {
2
const arr = new Array(n).fill(0).map(() => new Array(n).fill(0));
3
let count = 1,
4
index = 1,
5
i = 0,
6
j = 0,
7
changed = false,
8
toIncrease = true;
9
arr[i][j] = index;
10
while (index < n * n) {
11
index++;
12
if (i == n - count && j > count - 1) {
13
j--;
14
toIncrease = false;
15
changed = true;
16
} else if (i !== n - count && j == n - count) {
17
i++;
18
toIncrease = false;
19
changed = true;
20
}
21
if (i == count - 1 && !changed) {
22
if (toIncrease) j++;
23
else j--;
24
} else if (j == count - 1 && !changed) {
25
if (i == count) {
26
toIncrease = true;
27
j++;
28
count++;
29
} else if (toIncrease) i++;
30
else i--;
31
}
32
arr[i][j] = index;
33
if (index == 4 * (n - 1)) {
34
toIncrease = true;
35
count++;
36
}
37
changed = false;
38
}
39
return arr;
40
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0