# overlapping intervals

Write a function that returns the interval common to two given intervals, or the empty list if the given intervals are disjoint.

``` \$ cat io.rkt
#lang racket

(define (disjoint-intervals i1 i2)

; Return true iff the intersection of the given closed intervals is empty.

(define (common-interval i1 i2)

; Return the closed interval common to the two given closed intervals,
; assuming the given intervals have a non-empty intersection.

(define (interval-overlap-1 i1 i2)

; Return the closed interval representing the intersection of the given
; closed intervals or the empty list if the given intervals don't overlap.

(if (disjoint-intervals i1 i2)
'()
(common-interval i1 i2)))

(define (intersecting-intervals i1 i2)

; Return true iff the given closed intervals intersect.

(let

((i1s (car i1))
(i2s (car i2))

(cond

((< i1s i2s)
(>= i1e i2s))

((= i1s i2s)
#t)

((> i1s i2s)
(<= i1s i2e)))))

(define (interval-overlap-2 i1 i2)

; Return the closed interval representing the intersection of the given
; closed intervals or the empty list if the given intervals don't overlap.

(if (intersecting-intervals i1 i2)
(common-interval i1 i2)
'()))

(require rackunit)

(check-equal? (interval-overlap-1 '(19 25) '(22 30)) '(22 25))
(check-equal? (interval-overlap-2 '(19 25) '(22 30)) '(22 25))
(check-equal? (interval-overlap-1 '(19 25) '(12 17)) '())
(check-equal? (interval-overlap-2 '(19 25) '(12 17)) '())

(check-equal? (interval-overlap-1 '(22 30) '(19 25)) '(22 25))
(check-equal? (interval-overlap-2 '(22 30) '(19 25)) '(22 25))
(check-equal? (interval-overlap-1 '(12 17) '(19 25)) '())
(check-equal? (interval-overlap-2 '(12 17) '(19 25)) '())

(define (rand-int)
(let* ((n 1000)
(s (random (- (/ n 2)) n)))
(list s (+ s (random n)))))

(let loop ((i 0))
(when (< i 1000)
(let ((i1 (rand-int))
(i2 (rand-int)))
(check-equal? (interval-overlap-1 i1 i2) (interval-overlap-2 i1 i2))
(check-equal? (interval-overlap-2 i1 i2) (interval-overlap-2 i2 i1))
(loop (+ i 1)))))

\$ racket io.rkt

\$
```