如何在javascript中创建一个矩阵[已关闭]

rqenqsqc  于 2023-01-16  发布在  Java
关注(0)|答案(1)|浏览(120)

编辑问题以包含desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem。这将有助于其他人回答问题。
9小时前关门了。
Improve this question
我试图做一个矩阵,但我无法看到我的代码有什么问题。
预期结果:enter image description here
收到的结果:enter image description here
x一个月一次x一个月一次x一个月二次x一个月三次
x1名4名1 x 1名5名1 x 1名6名1 x 1名7名1 x
x一个八个一个x一个九个一个x一个十个一个x一个十个一个x一个十个x一个十个一个x一个十个x一个
while (c <= (Math.pow(n,2))){

for(x = inicio; x <= nlimite; x++ ){
    matriz[inicio][x] = c;
    c++;
}

for(x = inicio+1; x <= nlimite; x++ ){
matriz[x][nlimite] = c;
c++;

}

for(x = nlimite-1; x >= inicio; x-- ){
matriz[nlimite][x] = c;
c++;

}

for(x = nlimite-1; x >= inicio+1; x--){
matriz[x][inicio] = c;
c++;

x 1米16英寸x 1米17英寸
x一米十八英寸x一米十九英寸

juud5qan

juud5qan1#

function spiralMatrix(n) {
    const arr = Array.from({ length: n }, () => []);
    let row = 0;
    let col = 0;
    let rowEnd = n - 1;
    let colEnd = n - 1;
    let counter = 1;
    while (col <= colEnd && row <= rowEnd) {

        // Top row & middle value (Where col === colEnd && row === rowEnd)
        for (let i = col; i <= colEnd; i++) {
            arr[row][i] = counter;
            counter++;
        }
        row++;

        // end column
        for (let i = row; i <= rowEnd; i++) {
            arr[i][colEnd] = counter;
            counter++;
        }
        colEnd--;

        // end row
        for (let i = colEnd; i >= col; i--) {
            arr[rowEnd][i] = counter;
            counter++;
        }
        rowEnd--;

        // First col from end
        for (let i = rowEnd; i >= row; i--) {
            arr[i][col] = counter;
            counter++;
        }
        col++;
    }
    return arr;
}

输出:

相关问题