AlgoDaily Solution
1var assert = require('assert');
2
3function spiraltraverse(inmatrix) {
4 if (!inmatrix.length) return [];
5 const res = [];
6 const dirs = [
7 [0, 1],
8 [1, 0],
9 [0, -1],
10 [-1, 0],
11 ];
12 const scope = [inmatrix[0].length, inmatrix.length - 1];
13 let d = 0,
14 r = 0,
15 c = -1;
16 while (scope[d % 2] > 0) {
17 for (let i = 0; i < scope[d % 2]; i++) {
18 r += dirs[d][0];
19 c += dirs[d][1];
20 res.push(inmatrix[r][c]);
21 }
22 scope[d % 2]--;
23 d = (d + 1) % 4;
24 }
25 return res;
26}
27
28try {
29 assert.equal(
30 spiraltraverse([
31 [1, 2, 3, 4, 5, 6],
32 [7, 8, 9, 10, 11, 12],
33 ]),
34 '1,2,3,4,5,6,12,11,10,9,8,7'
35 );
36
37 console.log(
38 'PASSED: `spiraltraverse([[1,2,3,4,5,6], [7,8,9,10,11,12]])` should return `1,2,3,4,5,6,12,11,10,9,8,7 `'
39 );
40} catch (err) {
41 console.log(err);
42}
43
44try {
45 assert.equal(
46 spiraltraverse([
47 [1, 2, 3, 4],
48 [5, 6, 7, 8],
49 [9, 10, 11, 12],
50 [13, 14, 15, 16],
51 ]),
52 '1,2,3,4,8,12,16,15,14,13,9,5,6,7,11,10'
53 );
54
55 console.log(
56 'PASSED: `spiraltraverse([[1,2,3,4], [5,6,7,8 ], [9,10,11,12], [13,14,15,16]])` should return `1,2,3,4,8,12,16,15,14,13,9,5,6,7,11,10`'
57 );
58} catch (err) {
59 console.log(err);
60}
61
62try {
63 assert.equal(
64 spiraltraverse([
65 [1, 2],
66 [3, 4],
67 [5, 6],
68 [7, 8],
69 ]),
70 '1,2,4,6,8,7,5,3'
71 );
72
73 console.log(
74 'PASSED: `spiraltraverse([[1, 2], [3,4], [5,6], [7,8]])` should return `1,2,4,6,8,7,5,3`'
75 );
76} catch (err) {
77 console.log(err);
78}
Community Solutions
Community solutions are only available for premium users.
Access all course materials today
The rest of this tutorial's contents are only available for premium members. Please explore your options at the link below.
xxxxxxxxxx
58
var assert = require('assert');
function spiraltraverse(inmatrix) {
// fill this in
}
try {
assert.equal(
spiraltraverse([
[1, 2, 3, 4, 5, 6],
[7, 8, 9, 10, 11, 12],
]),
'1,2,3,4,5,6,12,11,10,9,8,7'
);
console.log(
'PASSED: `spiraltraverse([[1,2,3,4,5,6], [7,8,9,10,11,12]])` should return `1,2,3,4,5,6,12,11,10,9,8,7 `'
);
} catch (err) {
console.log(err);
}
try {
assert.equal(
spiraltraverse([
[1, 2, 3, 4],
[5, 6, 7, 8],
OUTPUT
Results will appear here.