现在有一个二维坐标组成的数组,例如
[[0,7],[8,10],[12,19],[13,15],[2,9],[19,22],[25,27],[30,33]];
这些坐标可以按照以下规则进行转换,例如:
1.坐标之间可以组成连续的坐标,则这些坐标可以转化为一个坐标,
[0,7] & [8,10] -> [0,10]
2.坐标之间存在包含关系,则这些坐标可以转换为一个坐标,
[12,19] & [13,15] -> [12,19]
需要经过重新计算将数组内的坐标转换为唯一坐标(即 既不包含(或者被包含)其他坐标,也不能和其他坐标连续的坐标),例子里的坐标的转化结果为:
[[0,7],[8,10],[12,19],[13,15],[2,9],[19,22],[25,27],[30,33]]
->
[[0,10],[12,22],[25,27],[30,33]]
请写出转化算法:
def merge(list):
def by_rule_merge_ranges(list):
merge_list = []
def _merge(ranges):
copy_ranges = copy.deepcopy(ranges)
ranges_length = len(ranges)-1
start_offset = copy_ranges[0][0]
end_offset = copy_ranges[0][1]
for j in range(ranges_length):
if j < ranges_length:
next_start_offset = ranges[j + 1][0]
next_end_offset = ranges[j + 1][1]
if start_offset <= (next_end_offset + 1) and start_offset >= next_start_offset and end_offset >= next_end_offset:
start_offset = next_start_offset
copy_ranges.remove(ranges[j+1])
elif end_offset >= (next_start_offset - 1) and end_offset <= next_end_offset and start_offset <= next_start_offset:
end_offset = next_end_offset
copy_ranges.remove(ranges[j + 1])
elif start_offset >= next_start_offset and end_offset <= next_end_offset:
start_offset = next_start_offset
end_offset = next_end_offset
copy_ranges.remove(ranges[j + 1])
elif start_offset <= next_start_offset and end_offset >= next_end_offset:
copy_ranges.remove(ranges[j + 1])
copy_ranges.remove(copy_ranges[0])
merge_list.append({
'startOffset': start_offset,
'endOffset': end_offset,
'count': 0
})
if len(copy_ranges) == 0:
return
else:
_merge(copy_ranges)
_merge(list)
return merge_list