Overlap
June 8, 2018
We have today a simple exercise to spice up your Friday lunch hour:
A range of integers is specified by its endpoints; for instance, the range [19, 25] includes the values 19, 20, 21, 22, 23, 24, and 25. The overlap of two ranges is those values that appear in both; for instance, given the ranges [19, 25] and [22, 30], the overlap is the range [22, 25]. The ranges [19, 25] and [12, 17] have no overlap.
Your task is to write a program that takes the endpoints of two ranges and returns their overlap, or reports that they have no overlap. When you are finished, you are welcome to read or run a suggested solution, or to post your own solution or discuss the exercise in the comments below.
In Ruby. Using Ranges (built-in)
Outout:
22..25
nil
Here’s a solution in C.
Example:
A Haskell version. For clarity we create a type for ranges.
Python
[22, 23, 24, 25]
[]
Here’s a solution in Python.
Output:
Mumps version
Klong version
racket version
Testing