1

我知道那里有类似的问题(我找到的最接近的问题是这个JavaScript;n 维数组创建)但其中大多数是在 Python 中,甚至我发现我试图在我的代码中实现的这个问题并没有奏效.

所以我想创建一个函数createGrid(L,n),它以两个相同大小的数组 L 和 n 作为参数。其中,L[i] 将指定第 i 维中网格的大小,而 n[i] 将指定同一维中的点数(例如点之间的间距为 L[i]/(n[i] - 1). 例如,对于二维,假设我调用“ let grid = createGrid([10,10],[2,2])”,那么函数应该返回一个 n+1 维数组,如下所示:[[[0,0],[0,10]], [[10,0 ],[10,10]]。

因此,如果我想访问网格中的一个点,我可以简单地键入,例如,grid[1][0],它将返回点 [10,0]。

在这一刻,我将其硬编码为 3 个维度,如下所示:

let create3DSquareGrid = function(L, n){
    //L should be an array [Lx, Ly, Lz], if not they are all the same
    if(!Array.isArray(L)){
        L = [L,L,L];
    }
    //n should be an array [nx, ny, nz], if not they are all the same
    if(!Array.isArray(n)){
        n = [n,n,n];
    }
    //calculate the dl of each dimension
    var dl = L.map((val,i)=> Math.round(val/(n[i]-1)));
    
    //create the grid
    let grid = []
    for(let i=0; i<n[0]; i++){
        let x = i*dl[0];
        let gridJ = [];
        for(let j=0; j<n[1]; j++){
            let y = j*dl[1];
            let gridK = [];
            for(let k=0; k<n[2]; k++){
                let z = k*dl[2];
                gridK.push([x,y,z]);
            }
            gridJ.push(gridK)
        }
        grid.push(gridJ);
    }
    return grid;
}

但我想将它扩展到任意数量的维度。我试图递归,如我一开始链接的问题所示,但它根本不起作用,所以我稍微调整了一下,事情变得更糟,从那时起,我开始变得越来越困惑。如果可以,请帮忙!非常感谢!

4

1 回答 1

1

您可以使用循环。这是解决这个问题的好方法。

function createGrid(L, n) {
    var ans = L
    for (i = 1; i < L.length; i++) {
        var tmp = []
        for (el of ans) {
            innerTmp = []
            for (j = 0; j < L.length; j++) {
                innerTmp.push([el, L[j]])
            }
            tmp.push(innerTmp)
        }
        ans = tmp
    }
    return ans
}
于 2020-11-11T12:55:32.580 回答