tbody> <<tr>"text-align:中心;"(1,1) (0,1) "text-align:中心;"(1,1) (1,0) (0,0) (1,0) (1,1) (0,1) "text-align:中心;"(1,1)
我有一个变量obj
,它具有需要笛卡尔坐标的元素计数。
我想生成下面的矩阵
obj
= 9,根号obj
= 3,3x3矩阵
tbody> <<tr>如果我没理解错的话,你想让坐标按顺序排列,这样左上角是第一个,右下角是最后一个,对吗?
你可以这样试试
let
size = 81, //ie a 7x7 grid,
rc = Math.floor(Math.sqrt(size)) //number of rows/columns
max = Math.floor(rc / 2), //maximum x and y coordinates
min = -1 * max; //minimim x and y coordinates
coords = [] //the array of coordinates
//as the positive y coordinates should be first, iterate from max down to min
for (let y = max; y >= min; y--)
//for each row, iterate the x cooridinates from min up to max
for (let x = min; x <= max; x++)
coords.push([x,y]);
for (let i = 0; i < rc; i++) {
let row = coords.slice(i*rc, (i+1)*rc); //get one full row of coordinates
console.log(row.map(x => formatCoordinate(x)).join("")); //and display it
}
function formatCoordinate(x) {
return "|" + `${x[0]}`.padStart(3, " ") + "/" + `${x[1]}`.padStart(3, " ") + "|"
}
另一种方法是,将坐标按任意顺序放入数组中,然后对值进行排序。但你必须按x
和y
坐标排序,
let
size = 81, //ie a 7x7 grid,
rc = Math.floor(Math.sqrt(size)) //number of rows/columns
max = Math.floor(rc / 2), //maximum x and y coordinates
min = -1 * max; //minimim x and y coordinates
coords = [] //the array of coordinates
//coords will be [[-3, -3], [-3, -2], [-3, -1] ..., [3, 3]]
for (let i = min; i <= max; i++)
for (let j = min; j <= max; j++)
coords.push([i,j]);
//sort coords to be [[-3, 3], [-2, 3], [-1, 3], ... [3, -3]]
coords.sort((a, b) => {
if (a[1] != b[1]) //if y coordinates are different
return b[1] - a[1]; //higher y coordinates come first
return a[0] - b[0]; //lower x coordinates come firs
})
for (let i = 0; i < rc; i++) {
let row = coords.slice(i*rc, (i+1)*rc); //get one full row of coordinates
console.log(row.map(x => formatCoordinate(x)).join("")); //and display it
}
function formatCoordinate(x) {
return "|" + `${x[0]}`.padStart(3, " ") + "/" + `${x[1]}`.padStart(3, " ") + "|"
}
两种方法都假设size
是奇数的平方,但你当然可以以任何你想要的方式调整它们,即原则上你只需要将min
和max
设置为任何你想要的值,两种方法都将从[[min/max] ... [max/min]]
创建一个坐标的平方。