Agn*_*ian 11 algorithm geometry coordinates line-segment computational-geometry
给定两条共线线段AB和CD,如何找到它们是否重叠?如何找到重叠的起点和终点?
以下是我正在使用的方法.我首先确保A <B和C <D.
if(pa < pc){
if(pc < pb){
if(pd < pb){
// overlap exists; CD falls entirely within AB
}
else {
// overlap exists; CB is the overlapping segment
}
}
else {
// no overlap exists; AB lies before CD
}
}
else {
if(pa < pd){
if(pb < pd){
// overlap exists; AB lies entirely within CD
}
else {
// overlap exists; AD is the overlapping segment
}
}
else {
// no overlap exists; CD lies before AB
}
}
Run Code Online (Sandbox Code Playgroud)
现在,有没有更简单的解决方案呢?
更新:还有另一种方法...比较两个段的长度之和与最外点之间的距离.如果后者较小,则存在重叠.
小智 17
确保A <B,C <D:
if (pb - pc >= 0 and pd - pa >=0 ) { // overlap
OverlapInterval = [ max(pa, pc), min(pb, pd) ] // it could be a point [x, x]
} // else: not overlap
Run Code Online (Sandbox Code Playgroud)