Skip to content

Commit 26b0cce

Browse files
author
Connor Leech
committed
add sprial matrix
1 parent 878d750 commit 26b0cce

File tree

1 file changed

+63
-0
lines changed

1 file changed

+63
-0
lines changed
Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
// --- Directions
2+
// Write a function that accepts an integer N
3+
// and returns a NxN spiral matrix.
4+
// --- Examples
5+
// matrix(2)
6+
// [[undefined, undefined],
7+
// [undefined, undefined]]
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 results = [];
20+
21+
for (let i = 0; i < n; i++) {
22+
results.push([]);
23+
}
24+
25+
let counter = 1;
26+
let startColumn = 0;
27+
let endColumn = n - 1;
28+
let startRow = 0;
29+
let endRow = n - 1;
30+
while (startColumn <= endColumn && startRow <= endRow) {
31+
// Top row
32+
for (let i = startColumn; i <= endColumn; i++) {
33+
results[startRow][i] = counter;
34+
counter++;
35+
}
36+
startRow++;
37+
38+
// Right column
39+
for (let i = startRow; i <= endRow; i++) {
40+
results[i][endColumn] = counter;
41+
counter++;
42+
}
43+
endColumn--;
44+
45+
// Bottom row
46+
for (let i = endColumn; i >= startColumn; i--) {
47+
results[endRow][i] = counter;
48+
counter++;
49+
}
50+
endRow--;
51+
52+
// start column
53+
for (let i = endRow; i >= startRow; i--) {
54+
results[i][startColumn] = counter;
55+
counter++;
56+
}
57+
startColumn++;
58+
}
59+
60+
return results;
61+
}
62+
63+
module.exports = matrix;

0 commit comments

Comments
 (0)