File tree Expand file tree Collapse file tree 1 file changed +45
-0
lines changed Expand file tree Collapse file tree 1 file changed +45
-0
lines changed Original file line number Diff line number Diff line change
1
+ 'use strict' ;
2
+ function constructMagicSumMatrix ( n ) {
3
+ let matrix = new Array ( n ) ;
4
+ for ( let index = 0 ; index < matrix . length ; index ++ )
5
+ matrix [ index ] = new Array ( index ) ;
6
+ for ( let i = 0 ; i < n ; i ++ ) {
7
+ for ( let j = 0 ; j < n ; j ++ ) {
8
+ matrix [ i ] [ j ] = - 1 ;
9
+ }
10
+ }
11
+ let i = 0 ,
12
+ j = parseInt ( ( n / 2 ) ) ,
13
+ num = 1 ;
14
+ while ( num <= ( n * n ) ) {
15
+ if ( i == - 1 && j == - 1 ) {
16
+ i = 1 ;
17
+ j = 0 ;
18
+ } else {
19
+ if ( i == - 1 ) i = n - 1 ;
20
+ if ( j == - 1 ) j = n - 1 ;
21
+ }
22
+ if ( matrix [ i ] [ j ] != - 1 ) {
23
+ i = i + 2 ;
24
+ j ++ ;
25
+ continue ;
26
+ } else matrix [ i ] [ j ] = num ++ ;
27
+
28
+ i -- ;
29
+ j -- ;
30
+ }
31
+ return matrix ;
32
+ }
33
+
34
+ function displayMatrix ( matrix , n ) {
35
+ for ( let i = 0 ; i < n ; i ++ ) {
36
+ let row = '' ;
37
+ for ( let j = 0 ; j < n ; j ++ ) {
38
+ row = row + matrix [ i ] [ j ] + ' ' ;
39
+ }
40
+ console . log ( row ) ;
41
+ }
42
+ }
43
+ let n = 7 ;
44
+ let magicMatrix = constructMagicSumMatrix ( n ) ;
45
+ displayMatrix ( magicMatrix , n ) ;
You can’t perform that action at this time.
0 commit comments