题目
把矩形的层级包含关系表示出来即可。
比如上面的图表示为一个 div 下有两个 div。
数据
r1 = [
{ id: 1, x1: 533, y1: 30, x2: 860, y2: 409 },
{ id: 2, x1: 559, y1: 49, x2: 837, y2: 207 },
{ id: 3, x1: 568, y1: 236, x2: 832, y2: 364 },
]
xy 是坐标信息,层级关系可根据此内容计算。
要处理成的数据
r2 = [
{
id: 1, x1: 533, y1: 30, x2: 860, y2: 409,
child: [
{ pid: 1, id: 2, x1: 559, y1: 49, x2: 837, y2: 207, },
{ pid: 1, id: 3, x1: 568, y1: 236, x2: 832, y2: 364, },
],
},
]
解
function checkInclude(data1, data2) {
return data2.x1 > data1.x1 && data2.y1 > data1.y1 &&
data2.x2 < data1.x2 && data2.y2 < data1.y2
}
function dep(arr, data) {
for (let i = 0; i < arr.length; i++) {
// 在容器内
if (checkInclude(arr[i], data)) {
// 有子容器,进一步判断
if (arr[i].child) {
dep(arr[i].child, data, arr)
return
} else {
// 如果当前容器没有子容器
arr[i].child = [
{
...data,
pid: arr[i].id
}
]
return
}
}
}
arr.push(data)
}
function rectangleContains(data_) {
// 先进行排序,后续根据循序处理
const data = data_.sort((item1, item2) => item1.x1 - item2.x1)
const result = []
for (let i = 0; i < data.length; i++) {
dep(result, data[i])
}
return result
}
var r1 = [
{id: 1, x1: 10, y1: 10, x2: 20, y2: 20},
{id: 2, x1: 11, y1: 11, x2: 19, y2: 19},
{id: 4, x1: 12, y1: 12, x2: 18, y2: 18},
{id: 5, x1: 11, y1: 11, x2: 18, y2: 18},
{id: 6, x1: 20, y1: 20, x2: 18, y2: 18},
{id: 7, x1: 533, y1: 30, x2: 860, y2: 409},
{id: 8, x1: 559, y1: 49, x2: 837, y2: 207},
{id: 9, x1: 568, y1: 236, x2: 832, y2: 364},
]
console.log(rectangleContains(r1))
[
{
"id": 1, "x1": 10, "y1": 10, "x2": 20, "y2": 20,
"child": [
{
"id": 2, "x1": 11, "y1": 11, "x2": 19, "y2": 19, "pid": 1,
"child": [
{
"id": 4, "x1": 12, "y1": 12, "x2": 18, "y2": 18, "pid": 2
},
{
"id": 6, "x1": 20, "y1": 20, "x2": 18, "y2": 18
}
]
},
{
"id": 5, "x1": 11, "y1": 11, "x2": 18, "y2": 18
}
]
},
{
"id": 7, "x1": 533, "y1": 30, "x2": 860, "y2": 409,
"child": [
{
"id": 8, "x1": 559, "y1": 49, "x2": 837, "y2": 207, "pid": 7
},
{
"id": 9, "x1": 568, "y1": 236, "x2": 832, "y2": 364
}
]
}
]
扁平转树的需求层出不穷,但解法都类似,循环|循环+递归…