我有一个可能会相互碰撞的矩形数组。我想用最小的减少量过滤出已经发生碰撞的矩形。有什么最优的方法吗?
以下是一些代码来说明上下文:
以下是一些代码来说明上下文:
type Rect = {
x: number;
y: number;
width: number;
height: number;
};
function isRectsColliding(rect1: Rect, rect2: Rect) {
return !(
rect1.x > rect2.x + rect2.width ||
rect1.x + rect1.width < rect2.x ||
rect1.y > rect2.y + rect2.height ||
rect1.y + rect1.height < rect2.y
);
}
const rects = [
{ x: 0, y: 181, width: 6, height: 6 },
{ x: 6, y: 147, width: 6, height: 6 },
{ x: 32, y: 124, width: 6, height: 6 },
{ x: 34, y: 7, width: 6, height: 6 },
{ x: 35, y: 11, width: 6, height: 6 },
{ x: 36, y: 0, width: 6, height: 6 },
{ x: 39, y: 15, width: 6, height: 6 },
];
const filteredRectIndexes = rects.reduce(?).map((_, idx) => idx); // should be [0, 1, 2, 3, 5, 6]
谢谢。
reduce
函数可能无法实现。直接的方法(不一定是最快的)是生成所有可能的子集,然后消除那些存在碰撞的子集。从剩下的集合中选择最大的一个... - derpirscher