|
type Line = [number, number] |
|
const isOverlap = (a: Line, b: Line) => !(a[0] > b[1] || b[0] > a[1]) |
|
|
|
const mergeTwoLines = (a: Line, b: Line): Line => [ |
|
Math.min(a[0], b[0]), |
|
Math.max(a[1], b[1]) |
|
] |
|
|
|
const mergeLines = (lines: Line[]) => { |
|
for (let i = 0; i < lines.length - 1; i ++) { |
|
for (let j = 1; j < lines.length - 1; j ++) { |
|
const a = lines[i] |
|
const b = lines[j] |
|
if (isOverlap(a, b)) { |
|
lines.splice(i, 1, null) |
|
lines.splice(j, 1, null) |
|
const nextLines = lines.filter(l => l) |
|
return mergeLines([mergeTwoLines(a, b), ...nextLines]) |
|
} |
|
return lines |
|
} |
|
} |
|
return lines |
|
} |
|
|
|
const sortLines = (lines: Line[]) => lines.sort((a, b) => a[1] - b[0]) |
|
|
|
const conactLines = (a: Line, b: Line) => { |
|
return [a[1], b[0]] |
|
} |
|
|
|
|
|
function insertLine(newLine: Line, lines: Line[]) { |
|
// 合并线段并排序 |
|
const sortedMergedLines = sortLines(mergeLines(lines)) |
|
// 找到空余的互补线段 |
|
const complementLines = [] |
|
sortedMergedLines.forEach((line, i, lines) => { |
|
const nextLine = lines[i + 1] || [Infinity, Infinity] |
|
complementLines.push(conactLines(line, nextLine)) |
|
}) |
|
// 找到空余线段与要插入的线段相交的地方就是要插入的地方 |
|
return complementLines.find(line => isOverlap(line, newLine)) |
|
} |
|
|
|
const line: Line = [5, 6] |
|
const lines: Line[] = [[1,4], [2,3], [4,5], [7,9]] |
|
console.log( insertLine(line, lines) ) |