File tree

2 files changed

+77
-0
lines changed

2 files changed

+77
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
// --- Directions
2+
// Write a function that accepts an integer N
3+
// and returns a NxN spiral matrix.
4+
// --- Examples
5+
// matrix(2)
6+
// [[1, 2],
7+
// [4, 3]]
8+
// matrix(3)
9+
// [[1, 2, 3],
10+
// [8, 9, 4],
11+
// [7, 6, 5]]
12+
// matrix(4)
13+
// [[1, 2, 3, 4],
14+
// [12, 13, 14, 5],
15+
// [11, 16, 15, 6],
16+
// [10, 9, 8, 7]]
17+
18+
function matrix(n) {
19+
const result = []
20+
let counter=1, startRow=0, endRow=n-1, startCol=0, endCol=n-1
21+
for(let i=0; i<n; i++){
22+
result.push([])
23+
}
24+
25+
while(startRow<=endRow && startCol<=endCol){
26+
//Top
27+
for(let i=startCol; i<=endCol; i++){
28+
result[startRow][i] = counter
29+
counter++
30+
}
31+
startRow++
32+
33+
//Right
34+
for(let i=startRow; i<=endRow; i++){
35+
result[i][endCol] = counter
36+
counter++
37+
}
38+
endCol--
39+
40+
//Bottom
41+
for(let i=endCol; i>=startCol; i--){
42+
result[endRow][i] = counter
43+
counter++
44+
}
45+
endRow--
46+
//Left
47+
for(let i=endRow; i>=startRow; i--){
48+
result[i][startCol] = counter
49+
counter++
50+
}
51+
startCol++
52+
}
53+
54+
return result
55+
}
56+
57+
console.log(matrix(6));
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
// --- Directions
2+
// Write a function that accepts an integer N
3+
// and returns a NxN spiral matrix.
4+
// --- Examples
5+
// matrix(2)
6+
// [[1, 2],
7+
// [4, 3]]
8+
// matrix(3)
9+
// [[1, 2, 3],
10+
// [8, 9, 4],
11+
// [7, 6, 5]]
12+
// matrix(4)
13+
// [[1, 2, 3, 4],
14+
// [12, 13, 14, 5],
15+
// [11, 16, 15, 6],
16+
// [10, 9, 8, 7]]
17+
18+
function matrix(n) {}
19+
20+
console.log(matrix(4));

0 commit comments

Comments
 (0)