尝试让我的头脑了解这个数学。我有一个网格,我想知道该 block 距离中心有多远。
我有一个当前的函数如下:
let grid = [];
function buildGrid(c, r) {
for(let i = 1; i <= r; i++) {
for(let j = 1; j <= c; j++) {
}
}
}
buildGrid(5, 3);
我希望它网格化输出如下:
let grid = [{x: -2, y: -1},
{x: -1, y: -1},
{x: 0, y: -1},
{x: 1, y: -1},
{x: 2, y: -1},
{x: -2, y: 0},
{x: -1, y: 0},
{x: 0, y: 0},
{x: 1, y: 0},
{x: 2, y: 0},
{x: -2, y: 1},
{x: -1, y: 1},
{x: 0, y: 1},
{x: 1, y: 1},
{x: 2, y: 1}];
或者
-2, -1 | -1, -1 | 0, -1 | 1, -1 | 2, -1
-------|--------|-------|-------|-------
-2, 0 | -1, 0 | 0, 0 | 1, 0 | 2, 0
-------|--------|-------|-------|-------
-2, 1 | -1, 1 | 0, 1 | 1, 1 | 2, 1
任何帮助将不胜感激。
最佳答案
回答正向流,例如 buildGrid(5, 3)
或 buildGrid(7, 5)
或 buildGrid(5, 3)
,表示大于 1 的偶数,不添加其他条件。我想你可以自己做这件事。如果您获得并发布了示例数据,请共享所有条件。
function buildGrid(c, r) {
var c_less = (c-1)/2;// You need to modify here to add all condition
var r_less = (r-1)/2;// You need to modify here to add all condition
//console.log(c_less);
var newArr = [];
for(let j = -r_less; j <= r_less; j++) {
var str = [];
for(let i = -c_less; i <= c_less; i++) {
str.push({x:i,y:j});
}
newArr.push(str);
}
document.querySelector("#output").innerHTML = JSON.stringify(newArr);
console.log(newArr);
}
buildGrid(5, 3);
<div id="output"></div>
var c_less = (c-1)/2;
//这里需要修改以添加所有其他条件
关于javascript - 中心为 0, 0 的矩阵网格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47460849/