Davide Mauri for Microsoft Azure

Posted on

# Advent of Code - Day 4

Day 4 - Camp Cleanup challenge is all about dealing with intervals. Intervals are trickier and more complex than one might think. No surprise the organizer of the Advent Of Code, included them in their challenges.

I did a lot of research on intervals, and specifically time intervals in the past, with a specific focus on how they can be applied to Business Intelligence and more specifically to Fact Table. Couple of slide decks I created lately on the subject are the following:

As usual I'm importing the input data and storing it into a table. Input data contains pairs of intervals, so I'm splitting the pairs and the interval begin and end into dedicated columns, for easier manipulation:

``````create table dbo.ch04_input
(
id int identity not null primary key,
pair1_b int,
pair1_e int,
pair2_b int,
pair2_e int
);

with cteLines as
(
select
trim(replace([value], char(13), '')) as [line]
from
string_split(@input, char(10))
),
ctePairs as
(
select
left([line], charindex(',', [line])-1) as pair1,
right([line], len([line]) - charindex(',', [line])) as pair2
from
cteLines
)
insert into
dbo.ch04_input (pair1_b, pair1_e, pair2_b, pair2_e)
select
left([pair1], charindex('-', [pair1])-1)  as pair1_b,
right([pair1], len([pair1]) - charindex('-', [pair1])) as pair1_e,
left([pair2], charindex('-', [pair2])-1) as pair2_b,
right([pair2], len([pair2]) - charindex('-', [pair2])) as pair2_e
from
ctePairs
``````

the result is the following:

## Part 1

The challenges ask to find all the pairs where one interval is completely included in the other. We must use the `CONTAINS` operator that can be expressed using simple math:

the query, therefore, is:

``````select
count(*)
from
ch04_input
where
(pair1_b >= pair2_b and pair1_e <= pair2_e) -- pair1 CONTAINS pair2
or
(pair2_b >= pair1_b and pair2_e <= pair1_e) -- pair2 CONTAINS pair1
``````

Challenge solved.

## Part 2

The second challenge requires to find all the pairs in which interval overlaps. There's an operator for that, and the math is even simpler:

The query then is:

``````select
count(*)
from
ch04_input a
where
(pair1_b <= pair2_e and pair2_b <= pair1_e) -- OVERLAPS
``````

Challenge completed.

## More content

Three friends of mine, Itzik Ben-Gan, Dejan Sarka and Adam Machanic were really passionate about this subject, and they shared a lot of content on the "interval" subject over the years. As the internet continuously changes and evolves, it is not easy to find those articles. Since the challenge was quite quick to finish, I used some of the budgeted time to try to find the updated link to such content. Here you go:

And this is an entire session on a subject that is very much related with intervals

Incredibly, I haven't been able to find anything from Adam...it seems the collapse of SqlBlog.com resulted in a lot of lost knowledge :(. I've reached out to him; Here's couple of post that are still available on the subject: