在Javascript中创建N维的点网格

问题描述

我知道那里也有类似的问题(我发现最接近的问题是这个JavaScript; n-dimensional array creation),但是大多数问题都在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;
}

但是我想将此扩展任意数量的尺寸。我试图按照开头所链接问题的说明进行递归,但是它根本没有用,所以我对其进行了一些调整,但情况变得更糟,从那时起,我变得越来越困惑。 如果可以的话,请帮忙!非常感谢!

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)