1
+
2
+ /**
3
+ * Facebook, prep: Question 1 - 2D Spiral array
4
+ * Find the pattern and complete the function:
5
+ * int[][] spiral(int n);
6
+ * where n is the size of the 2D array.
7
+ */
8
+ /**
9
+ * @param {number } n Size of the array
10
+ * @return {number[][] } Array populated in spiral way
11
+ */
12
+ const spiral = n => {
13
+ // Check edge case
14
+ if ( n <= 0 ) {
15
+ return [ ] ;
16
+ }
17
+
18
+ // 0 horizontally, 1 vertically
19
+ let axis = 0 ;
20
+ // 0 right/down, 1 left/up
21
+ let dir = 0
22
+ const area = n * n ;
23
+ let i = 0 ;
24
+ let j = 0 ;
25
+ let counter = 1 ;
26
+ const arr = Array ( n ) . fill ( ) . map ( ( ) => Array ( n ) . fill ( ) ) ;
27
+ arr [ i ] [ j ] = counter ;
28
+ counter ++ ;
29
+ bounds = [ 0 , n - 1 ] ;
30
+ // O(n^2) because the area is n * n and we loop the entire area
31
+ while ( counter <= area ) {
32
+ // Move in the current axis according to the current direction
33
+ if ( axis === 0 ) {
34
+ j = dir === 0 ? j + 1 : j - 1 ;
35
+ } else {
36
+ i = dir === 0 ? i + 1 : i - 1 ;
37
+ }
38
+ /*
39
+ * Check if the loop returned to the start.
40
+ * In that case, narrow the boundaries
41
+ */
42
+ if ( arr [ i ] [ j ] ) {
43
+ bounds [ 0 ] ++ ;
44
+ bounds [ 1 ] -- ;
45
+ i = bounds [ 0 ] ;
46
+ j = bounds [ 0 ] ;
47
+ arr [ i ] [ j ] = counter ;
48
+ axis = 0 ;
49
+ dir = 0 ;
50
+ } else {
51
+ arr [ i ] [ j ] = counter ;
52
+ /*
53
+ * Check if the loop is at the limit of Y axis.
54
+ * In that case, switch the direction and the axis
55
+ */
56
+ if ( ( i === bounds [ 1 ] || i === bounds [ 0 ] ) && axis === 1 ) {
57
+ axis = 0 ;
58
+ dir = i === 0 ? 0 : 1 ;
59
+
60
+ /*
61
+ * Check if the loop is at the limit of X axis.
62
+ * In that case, switch the axis
63
+ */
64
+ } else if ( ( j === bounds [ 1 ] || j === bounds [ 0 ] ) && axis === 0 ) {
65
+ axis = 1 ;
66
+ }
67
+ }
68
+ counter ++ ;
69
+ }
70
+ return arr ;
71
+ } ;
72
+
73
+ const n = 4 ;
74
+ const a = spiral ( n ) ;
75
+ for ( row of a ) {
76
+ console . log (
77
+ row . map ( el =>
78
+ el <= 9 ? `${ '0' . repeat ( ( n * n + '' ) . length - 1 ) } ${ el } ` : el . toString ( )
79
+ )
80
+ ) ;
81
+ }
0 commit comments