php - Fill gaps in a time schedule

283

A daily schedule starts at 08:30 and ends at 17:00 (time represented via a begin 'nn:nn' string and end 'nn:nn' string).

Time blocks can only begin and end on :00, :15, :30, :45 of the hour.

A given schedule will have zero or more (non-overlapping) blocks of time pre-booked (of variable block size--anything from one block of 8:30-17:00; or could be many small blocks of 15-minute, half hour, multi-hour blocks, etc).

Example Input:

$schedule = [
    [
        'begin' => '10:00',
        'end' => '12:30'
    ],
    [
        'begin' => '15:15',
        'end' => '16:00'
    ]
];

Example Output:

$gapFiller =
[
    [
        'begin' => '08:30',
        'end' => '10:00'
    ],
    [
        'begin' => '12:30',
        'end' => '15:15'
    ],
    [
        'begin' => '16:00',
        'end' => '17:00'
    ]
];

Create a function that returns an array of zero or more blocks to fill all the gaps present in an pre-booked schedule. Make block spans as large as possible without overlapping any other blocks.

function fillGaps($schedule){
    //code...

    return $gapFiller;
}

$gapFiller = fillGaps($schedule);
889

Answer

Solution:

This function will give you the desired result, based on the input being sorted with no overlaps:

function fillGaps($schedule) {
    $gaps = array();
    $time = strtotime('08:30');
    foreach ($schedule as $event) {
        if ($time < strtotime($event['begin']))
            $gaps[] = array('start' => date('H:i', $time), 'end' => $event['begin']);
        $time = strtotime($event['end']);
    }
    if ($time < strtotime('17:00'))
        $gaps[] = array('start' => date('H:i', $time), 'end' => '17:00');
    return $gaps;
}

Output for your sample data:

array (
  0 => 
  array (
    'start' => '08:30',
    'end' => '10:00',
  ),
  1 => 
  array (
    'start' => '12:30',
    'end' => '15:15',
  ),
  2 => 
  array (
    'start' => '16:00',
    'end' => '17:00',
  ),
)

Demo on rextester

People are also looking for solutions to the problem: php - Formatting dynamic timestamps

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.