-
Notifications
You must be signed in to change notification settings - Fork 23
/
Copy path11-the-matrix.js
57 lines (51 loc) · 1.02 KB
/
11-the-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
54
55
56
57
// --- Directions
// Write a function that accepts an integer N
// and returns a NxN spiral matrix.
// --- Examples
// matrix(2)
// [[1, 2],
// [4, 3]]
// matrix(3)
// [[1, 2, 3],
// [8, 9, 4],
// [7, 6, 5]]
// matrix(4)
// [[1, 2, 3, 4],
// [12, 13, 14, 5],
// [11, 16, 15, 6],
// [10, 9, 8, 7]]
function matrix(n) {
const result = []
let counter=1, startRow=0, endRow=n-1, startCol=0, endCol=n-1
for(let i=0; i<n; i++){
result.push([])
}
while(startRow<=endRow && startCol<=endCol){
//Top
for(let i=startCol; i<=endCol; i++){
result[startRow][i] = counter
counter++
}
startRow++
//Right
for(let i=startRow; i<=endRow; i++){
result[i][endCol] = counter
counter++
}
endCol--
//Bottom
for(let i=endCol; i>=startCol; i--){
result[endRow][i] = counter
counter++
}
endRow--
//Left
for(let i=endRow; i>=startRow; i--){
result[i][startCol] = counter
counter++
}
startCol++
}
return result
}
console.log(matrix(6));