我有一个显示网格的div,如下所示。
render() {
return (
<div style={{display: "grid", gridTemplateColumns: "10px 10px 10px 10px", gridTemplateRows: "10px 10px 10px 10px"}}>
{this.renderCells()}
</div>
);
}
在我的renderCells()函数中,我有。
renderCells = () => {
let render = [];
for(let i = 0; i < 16; i++)
render.push(<div className="cell" key={i} onClick={() => this.clickElement(i)}>{i}</div>);
return render;
}
它成功地生成了4x4的网格系统,里面有0...15个数字。在我的clickElement()函数中,我有。
const clickElement = (index) => {
this.array.push(index);
}
我想创建一个函数来检查this.array中的索引号是否可以创建一个矩形或正方形。
例子
Grid System
[0, 1, 2, 3]
[4, 5, 6, 7]
[8,9,10,11]
[12,13,14,15]
如果用户分别点击4、5、8和9,当我们运行isRectangleorSquare()函数后,它应该返回true,例如5、6、9应该返回false。
如何编写isRectangleorSquare()函数?
这个答案意味着你有一个javascript变量(在这个例子中叫做 "矩阵")来表示你的css网格。
你可以找到被选中的元素的坐标,并把它们放在一个列表中(例如4,5,8,9),然后得到左上角和右下角的坐标。
[
[1 (vertical), 0 (horizontal)]
[1, 1]
[2, 0]
[2, 9]
]
然后得到左上角和右下角的坐标。
这时,循环浏览你的原始矩阵,看看每个元素是否都在你的选择元素列表中。
这里是源码作为例子。
let matrix = [
[0, 1, 2, 3],
[4, 5, 6, 7],
[8, 9, 10,11],
[12,13,14,15]
];
let selected = [4,5,8,9];
function isRectangle(selected) {
let coords = [];
// get the coords (could be optimised)
for (let val of selected) {
for (let row = 0; row < matrix.length; row++) {
let idx = matrix[row].findIndex((x) => x == val);
if (idx > -1) {
coords.push([row, idx]);
}
}
}
// get the corners
let mtop = Math.min(...coords.map((c) => c[0]));
let mbottom = Math.max(...coords.map((c) => c[0]));
let mleft = Math.min(...coords.map((c) => c[1]));
let mright = Math.max(...coords.map((c) => c[1]));
// check the values
for (let i=mtop; i<=mbottom; i++) {
for (let c=mleft; c<=mright; c++) {
if (! selected.includes(matrix[i][c])) {
return false;
}
}
}
return true;
}
isRectangle(selected);
这段代码至少有两个方面可以改进。