[英]Finding Gaps in a Range of Number
I am looking for a solution (preferably JavaScript) that would find gaps in a select set of child ranges compared to their parent range. 我正在寻找一种解决方案(最好是JavaScript),它会在一组选定的子范围中找到与其父范围相比的差距。
Example 1: If I select a parent range of {1,10} and child ranges of {1,2} and {2,10} I would have a gap of 0, meaning the range in the parent range has been completely filled by it's children. 示例1:如果我选择父范围{1,10},子范围{1,2}和{2,10},则间隙为0,这意味着父范围中的范围已完全被这是孩子们。
Example 2: If I select a parent range of {1,10} and child ranges of {1-3} and {6,8} I would have a gap of 4. 示例2:如果我选择{1,10}的父范围和{1-3}和{6,8}的子范围,我将有4的间隙。
The resulting total is the number of missing numbers, assuming you're only using integers. 假设您只使用整数,结果总数是缺失数字的数量。
In general the gap will also be a range or set of ranges. 通常,间隙也是一系列范围或一组范围。 Example parent: {1-10}, children {1,2},{5,8}, gap {3,4},{9,10} because of this I would just suggest you write a thing which can subtract one range from another then apply it to the parent for each child. 示例父母:{1-10},孩子{1,2},{5,8},差距{3,4},{9,10}因此我建议你写一个可以减去一个范围的东西然后再将其应用于每个孩子的父母。 There are 3 cases to consider: is it at the start, in the middle (generating two ranges) or at the end. 有3种情况需要考虑:是在开头,中间(生成两个范围)还是结尾。 Then when you are subtracting from a set of ranges you have to consider all cases where there could be overlap. 然后,当您从一组范围中减去时,您必须考虑可能存在重叠的所有情况。
so in javascript make a range object with a start and end property then carry around arrays of these. 所以在javascript中创建一个具有start和end属性的范围对象,然后携带这些的数组。 The make a function rangeSub(parent, child) to do the subtraction where parent can be an array of ranges and child is a single range. 创建一个函数rangeSub(parent,child)进行减法,其中parent可以是范围的数组,child是单个范围。
rangeSub(parent, child) {
var result;
//code for set of range subtraction
if(parent.length)
for(range in parent) {
temp = rangeSub(range,child);
if(temp.length) result.concat(temp);
else result.push(temp);
}
return result;
}
//code for single range subtraction
if(parent.start < child.start) {
...
}
if(parent.end > child.end) {
...
}
etc.
}
There are still several edge cases to work out but this is the general form I would follow. 仍然有几个边缘情况需要解决,但这是我将遵循的一般形式。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.