Skip to content

Instantly share code, notes, and snippets.

@lotharthesavior
Last active June 4, 2022 00:55
Show Gist options
  • Save lotharthesavior/ab637fdf9e0c70ecdafd9508c994b2b4 to your computer and use it in GitHub Desktop.
Save lotharthesavior/ab637fdf9e0c70ecdafd9508c994b2b4 to your computer and use it in GitHub Desktop.
Finding the first available time for 2 users
<?php
/**
Give the data is this:
[
{
"name":"Joe",
"meetings":[
["06:00", "08:00"],
["08:15", "09:30"]
]
},
{
"name":"Sam",
"meetings":[
["08:00", "08:30"],
["12:00", "13:00"]
]
}
]
Step 1: divide into 2 meeting groups
Step 2: find wether the user 1 or 2 has the lastest end time
Step 3: find if the current end time also is the lastest for the second meeting
After this point, the points to scale are:
Available time for more users:
Option 1: group every 2 users and compare all of them with the same algorithm.
Option 2: recursion (this could also avoid multiple layer-loops)
*/
$meeting1 = ['meeting1' => [], 'meeting2' => []];
$meeting1['meeting1'][] = Carbon\Carbon::createFromFormat('H:i', '06:00');
$meeting1['meeting1'][] = Carbon\Carbon::createFromFormat('H:i', '08:00');
$meeting1['meeting2'][] = Carbon\Carbon::createFromFormat('H:i', '08:15');
$meeting1['meeting2'][] = Carbon\Carbon::createFromFormat('H:i', '09:30');
$meeting2 = ['meeting1' => [], 'meeting2' => []];
$meeting2['meeting1'][] = Carbon\Carbon::createFromFormat('H:i', '08:00');
$meeting2['meeting1'][] = Carbon\Carbon::createFromFormat('H:i', '08:30');
$meeting2['meeting2'][] = Carbon\Carbon::createFromFormat('H:i', '12:00');
$meeting2['meeting2'][] = Carbon\Carbon::createFromFormat('H:i', '13:00');
$timeslot = null;
foreach($meeting1 as $m) {
if (null !== $timeslot && $timeslot->between($m[0], $m[1])) {
$timeslot = null;
} elseif (null !== $timeslot) {
continue;
}
foreach($meeting2 as $m2) {
if (null !== $timeslot && $timeslot->between($m2[0], $m2[1])) {
$timeslot = null;
} elseif (null !== $timeslot) {
continue;
}
$start = $m2[0];
if ($m[0]->isBefore($m2[0])) {
$start = $m[0];
}
$end = $m2[1];
if ($m[1]->isAfter($m2[1])) {
$end = $m[1];
}
$timeslot = $end;
}
}
dd($timeslot);
@lotharthesavior
Copy link
Author

This is expected to be used within laravel environment. To make it generic PHP we need to replace Carbon and dd procedures.

@lotharthesavior
Copy link
Author

lotharthesavior commented Jun 4, 2022

Version 2 turned the solution to cover more possible cases.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment