2 回答
TA贡献1809条经验 获得超8个赞
我注意到你打电话给你的区段,而实际上,它们不是。因此,为了消除任何混淆,我决定将它们重命名为,然后创建一个单独的数组,该数组具有一些关于哪些段应该首先出现的逻辑。orderedSegmentsunOrderedSegmentsorderedSegments
然后,我编写了一个小的辅助函数,该函数查看两个段并决定它们是否相交/重叠。isOverlapping(a, b)
然后,我创建了一个数组,它将每个层作为单独的元素(段数组)保存。layers
逻辑很简单,如伪代码中所述:
loop through each `segment` in `orderedSegments`:
loop through each `layer` in `layers`:
check if the `segment` is overlaping any of the segments in the current `layer'
if not then insert the `segment` to the current `layer`
if yes, then check with the other layers
if we reach the end of layers but could not insert it in any,
then add the segment to its own new layer
const unOrderedSegments = [
[15, 18], // 1
[0.3, 9], // 2
[4, 13], // 3
[8, 14], // 4
[1, 3], // 5
[16, 19.5], // 6
[4.1, 17.5], // 7
[0, 2.9], // 8
[2.9, 11], // 9
[12.5, 19.4], // 10
[11.3, 12], // 11
];
const orderedSegments = unOrderedSegments.sort((a, b) => a[0] - b[0]);
const isOverlapping = (a, b) => {
const check1 = a[0] > b[0] && a[0] < b[1];
const check2 = b[0] > a[0] && b[0] < a[1];
return check1 || check2;
};
const layers = [];
for (let i = 0; i < orderedSegments.length; i++) {
const currentSegment = orderedSegments[i];
let inserted = false;
for (let j = 0; j < layers.length; j++) {
const currentLayer = layers[j];
let canBeInserted = true;
for (let k = 0; k < currentLayer.length; k++) {
const segment = currentLayer[k];
if (isOverlapping(segment, currentSegment)) {
canBeInserted = false;
break;
}
}
if (canBeInserted) {
currentLayer.push(currentSegment);
inserted = true;
break;
}
}
if (!inserted) {
layers.push([currentSegment]);
}
}
// print each layer on a spearate line
// ( convert array to string )
layers.forEach((layer) => {
let layerString = "";
layer.forEach((segment) => {
layerString += `[${segment[0]}-${segment[1]}]`;
});
console.log(layerString);
});
TA贡献1876条经验 获得超7个赞
const orderedSegments = [
[15, 18], // 1
[0.3, 9], // 2
[4, 13], // 3
[8, 14], // 4
[1, 3], // 5
[16, 19.5], // 6
[4.1, 17.5], // 7
[0, 2.9], // 8
[2.9, 11], // 9
[12.5, 19.4], // 10
[11.3, 12] // 11
]
// sort array by starting time (orderedSegments[i][0])
orderedSegments.sort((a, b) => {
if(a[0] < b[0]) return -1;
if(a[0] > b[0]) return 1;
return 0;
});
const newSegments = [];
while(orderedSegments.length > 0) {
// get first element of array
let element = orderedSegments[0];
// all "used" items will be removed. used items are marked with -1
if(element[0] == -1) {
orderedSegments.shift();
break;
}
// newElementGroup represents a new layer
let newElementGroup = [];
newElementGroup.push(element);
for(let i = 0; i < orderedSegments.length; i++) {
if(orderedSegments[i][0] > element[1]) {
element = orderedSegments[i].slice();
newElementGroup.push(element);
// mark element as "used"
orderedSegments[i][0] = -1;
}
}
newSegments.push(newElementGroup);
// remove first element after creating a new layer until orderedSegments is empty
orderedSegments.shift();
}
newSegments.forEach(element => console.info(element))
我想这应该可以解决问题
添加回答
举报