javascript - 中心为 0, 0 的矩阵网格

标签 javascript arrays matrix

尝试让我的头脑了解这个数学。我有一个网格,我想知道该 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/

相关文章:

javascript - 了解 ng-table 演示中的延迟排序示例

python - 使用 numpy 对数组进行排序以适合另一个数组

r - R 中错误的矩阵求逆结果

c++ - 在 C++ 中为矩阵的第一行赋值

javascript - 我应该等待文件准备好吗?

javascript - 使用 JavaScript 定位 Oracle APEX 表格形式列

javascript - Ngrx store dispatch 不接受字符串作为参数

java - 将 Short 转换为 3 字节数组

c - 函数 'memcpy' 的警告可能数据溢出是如何发生的以及如何修复它?

java - 有没有办法移动二维数组矩阵中的列?