Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit e5c7416

Browse files
author
Manjunath
committed
magic sum matrix
1 parent a4eac98 commit e5c7416

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed

‎Data-Structure/Array/2D/magicSum.js‎

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
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);

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /