さて、昨夜は退屈だったので、これを Python で行いました。それは不必要に再帰的です (私は The Little Schemer を読んだばかりで、現在、再帰は非常に優れていると思います) が、問題を解決し、私が投げたすべての入力を処理します。
intervals = [(0,4), (5,13), (8,19), (10,12)]
def overlaps(x,y):
x1, x2 = x
y1, y2 = y
return (
(x1 <= y1 <= x2) or
(x1 <= y2 <= x2) or
(y1 <= x1 <= y2) or
(y1 <= x2 <= y2)
)
def find_overlaps(intervals, checklist=None, pending=None):
if not intervals:
return []
interval = intervals.pop()
if not checklist:
return find_overlaps(intervals, [interval], [interval])
check = checklist.pop()
if overlaps(interval, check):
pending = pending or []
checklist.append(check)
checklist.append(interval)
return pending + [interval] + find_overlaps(intervals, checklist)
else:
intervals.append(interval)
return find_overlaps(intervals, checklist)
次のように使用します。
>>> find_overlaps(intervals)
[(10, 12), (8, 19), (5, 13)]
開始点の逆順ですべての重複する間隔を返すことに注意してください。うまくいけば、それは小さな問題です。これは、リストの先頭で動作するandではなく、リストの最後で動作するpush()
andを使用しているためです。pop()
insert(0)
pop(0)
これは完璧ではありませんが、線形時間で実行されます。また、実際の文字列のサイズはまったく問題ではないことも覚えておいてください。実行時間は、文字列のサイズではなく、間隔の数に比例します。