# Intersection of two points in Ruby

I want to find intersection of two points in Ruby. What type of checks should be there so that the function works for all cases.

Pseudocode code is

intersection(range1, range2)

• notCommonR1 = part of range1 which is not common

• common = common part between both ranges

• notCommonR2 = part of range2 which is not common

For example

```intersection([0, 3], [2, 4]) == {
:range1 => [[0, 2]],
:both => [2, 3],
:range2 => [[3, 4]]
}
```

This is fairly straightforward; there aren't really any special checks to make here; the only special case is if there is no common part between the ranges.

```def intersection(a, b)
# Sort so that a1 < a2, b1 < b2, a1 < b1
a, b = [a.sort, b.sort].sort
a1, a2 = a
b1, b2 = b

if a2 > b2
{range1: [[a1, b1], [b2, a2]], both: [[b1, b2]], range2: []}
elsif a2 >= b1
{range1: [[a1, b1]], both: [[b1, a2]], range2: [[a2, b2]]}
else
{range1: [[a1, a2]], both: [], range2: [[b1, b2]]}
end
end
```

Depending on how you use both, nil as a value may not be ideal; use whatever indicates no common range.

```def intersection((x1, x2), (x3, x4))
h = {}
e1, e2 = x1..x2, x3..x4
[x1, x2, x3, x4].sort.each_cons(2) do |x5, x6|
key =
case [e1, e2].select{|e| e.include?(x5..x6)}
when [e1] then :range1
when [e2] then :range2
when [e1, e2] then :both
end
h[key] ||= []
h[key].push([x5, x6])
end
h
end
```