K
K
Kirill Sidorov2013-12-16 06:34:13
Algorithms
Kirill Sidorov, 2013-12-16 06:34:13

What algorithm should be used to determine the availability of a time period?

I am developing a system of pre-registration through the site. Now I ran into a problem, I can’t figure out how to beautifully and correctly determine the right time is available or busy.
Some details:
There is an entity "Record", which has two main parameters: time and duration.
Let's say there are two such entities: (9:00, 30 min), (10:00, 1 hour). It is clear that (9:35, 1 hour) will already be invalid, since there is already an entry for 10.
What algorithm can be used? Don't ask for a code, just kick in the right direction.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
R
Rsa97, 2013-12-16
@cyberia

On reflection, I came up with:

SELECT count(*) AS x FROM records 
    WHERE (begin BETWEEN '{$newRecordBegin}' AND '{$newRecordEnd}') OR
          ('{$newRecordBegin}' BETWEEN begin AND end)

The first part of the condition - the beginning of some old record falls into the middle of the new one.
The second part - the beginning of a new record falls into the middle of an old one.
If at least one condition is met - count(*) > 0, you cannot insert a record.

S
sasha, 2013-12-16
@madmages

offhand it occurred to me to store the start time and end time in meringue and then just one SQL query to find out freely or not

R
Rsa97, 2013-12-16
@Rsa97

0. We try to insert a new record newRecordStart, newRecordLength
1. We get two records closest in time, one before (prevRecordStart, prevRecordLength) and one after the new one (nextRecordStart, nextRecordLength).
2. The new record must not overlap with the previous one:
(newRecordStart >= prevRecordStart+prevRecordLength)
3. The new record must not overlap with the next one:
(newRecordStart+newRecordLength <= nextRecordStart)
4. If both conditions are met, you can insert a record.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question