Last active
July 19, 2018 12:01
-
-
Save dondevi/024ab35f2a19d90f6a166929920f9eca to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 回形矩阵 | |
* @param {Number} n - 矩阵尺寸 | |
* @return {String} | |
*/ | |
function spiralMatrix (n) { | |
let matrix = []; | |
let a = n ** 2; | |
let p = a.toString().length; | |
for (let x = 0; x < n; x++) { | |
for (let y = 0; y < n; y++) { | |
let cx = n - 1 - x; | |
let cy = n - 1 - y; | |
let z = Math.min(x, y, cx, cy); | |
let m = n - z * 2; | |
let b = a - m ** 2; | |
let cb = b + (m - 1) * 2; | |
let v = x <= y ? (x - z) + (y - z) + b | |
: (cx - z) + (cy - z) + cb; | |
matrix.push(v.toString().padStart(p, " ")); | |
} | |
matrix.push("\n"); | |
} | |
return matrix.join(" ").replace(/\n\s/g, "\n"); | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
console.log(spiralMatrix(6)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment