螺旋数的一个解法
题目是: 给定一个自然数n,将n*n个数字按顺时针方向填入一个二维数组, 比如: n=4, 则结果为:
1 2 3 4 12 13 14 5 11 16 15 6 10 9 8 7
const count = 4
const result = []
for (let i = 0; i < count; i++){
result[i] = Array(count).fill(0)
}
for (let i = 0; i < count; i++){
for (let j = 0; j < count; j++) {
const round = Math.min(i, j, count - 1 - j, count - 1 - i)
if (i <= j){
result[i][j] = i + j + 1 + (count * round - round * round) * 4 - round*2
}else{
result[i][j] = (count * (round + 1) - (round + 1) * (round + 1)) * 4 - (i + j - 1) + round*2
}
}
}
result.forEach(row=>{
console.log(row.join('\t'))
})