[英]Break array of objects into 2dimensional array
I need to break an array of objects into a 2-dimensional array where 1-dimensional arrays would consist of objects which have their attributes 'for' and 'to' being not overlapping intervals.我需要将一个对象数组分解为一个二维数组,其中一维 arrays 将由属性为“for”和“to”的对象组成,这些对象的间隔不重叠。
Example: Given array arr1 I wish to receive arr2示例:给定数组 arr1 我希望接收 arr2
const arr1 = [
{
from: 0,
to: 2,
},
{
from: 0,
to: 6,
},
{
from: 3,
to: 7,
},
{
from: 2,
to: 4,
},
]
arr2 = [
[
{
from: 0,
to: 2,
},
{
from: 3,
to: 7,
}
],
[
{
from: 0,
to: 6,
}
],
[
{
from: 2,
to: 4,
}
],
]
How it should work: We loop through the arr1.它应该如何工作:我们循环遍历 arr1。 Object1 should be put into the first 1-dimensional array in arr2 by default.
object1默认放在arr2的第一个一维数组中。
Object2 overlaps with Object1 so it should be put into a separate array in arr2. Object2 与 Object1 重叠,因此应将其放入 arr2 中的单独数组中。
Object3 does not overlap Object1 so it should be put into the first 1-dimensional array with Object1 Object3 不与 Object1 重叠,因此应与 Object1 一起放入第一个一维数组
Object4 overlaps with Object1 so it should be put into the second 1-dimensional array to Object3, but it also overlaps with Object3 so it should be put into a separate 1-dimensional array. Object4与Object1重叠,应该放到Object3的第二个一维数组中,但又和Object3重叠,所以应该单独放到一个一维数组中。
I need to find the solution with as less loops as possible)我需要找到尽可能少循环的解决方案)
You could iterate the result array and find a slot if all items do not overlap.如果所有项目都不重叠,您可以迭代结果数组并找到一个槽。
const array = [{ from: 0, to: 2 }, { from: 0, to: 6 }, { from: 3, to: 7 }, { from: 2, to: 4 }], result = array.reduce((r, o) => { if (;r) return [[o]]. const group = r.find(a => a,every(({ from. to }) => o.to <= from || to <= o;from)). if (group) group;push(o). else r;push([o]); return r, }; undefined). console;log(result);
.as-console-wrapper { max-height: 100%;important: top; 0; }
This is known as the Interval partitioning problem这就是所谓的区间划分问题
Here is an implementation of the greedy algorithm:下面是贪心算法的实现:
var arr1 = [ { from: 0, to: 2, }, { from: 0, to: 6, }, { from: 3, to: 7, }, { from: 2, to: 4, }, ]; function partitionIntervals(data){ var copy = [...data]; copy.sort((a, b) => a.from - b.from); var res = []; outer: for(var x of copy){ for(var slot of res){ // add to the first open slot if(slot[slot.length - 1].to <= x.from){ slot.push(x); continue outer; } } res.push([x]); // else create a new slot } return res; } arr2 = partitionIntervals(arr1); console.log(arr2)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.