Skip to content

Instantly share code, notes, and snippets.

@andy-cline
Created October 23, 2016 13:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save andy-cline/6780cc0ea4afffca4b79f6856e60e0f5 to your computer and use it in GitHub Desktop.
Save andy-cline/6780cc0ea4afffca4b79f6856e60e0f5 to your computer and use it in GitHub Desktop.
Generate random seating assignments for a multi-session meeting.
$personTableAssignments = generateTableAssignments(8, 8);
foreach ($personTableAssignments as $personTableAssignment) {
echo (implode(', ', $personTableAssignment) . '<br />');
}
function generateTableAssignments($numSessions, $numTables)
{
$numPeople = $numSessions * $numTables;
$tableSessionCount = [];
$personTableAssignments = [];
for ($table = 0; $table < $numTables; $table++) {
// keep a count of the number of people at each table for each session.
$tableSessionCount[$table] = [0,0,0,0,0,0,0,0];
}
for ($person = 0; $person < $numPeople; $person++) {
// keep track of which tables a person has been assigned to
$personTableAssignments[$person] = [];
}
$numAssignmentsComplete = 0;
$numAssignmentsNeeded = $numPeople * $numTables;
while ($numAssignmentsComplete < $numAssignmentsNeeded) {
$randomListOfPeople = range(0, $numPeople - 1);
shuffle($randomListOfPeople);
foreach ($randomListOfPeople as $randomPerson) {
$randomListOfTables = range(0, $numTables - 1);
shuffle($randomListOfTables);
foreach (range(0, $numSessions - 1) as $sessionNumber) {
foreach ($randomListOfTables as $table) {
// make sure A) this person hasn't already been assigned to this table and
// B) that this table isn't already full for the session
if (!in_array($table, $personTableAssignments[$randomPerson]) && $tableSessionCount[$sessionNumber][$table] < 8) {
$numAssignmentsComplete++;
$personTableAssignments[$randomPerson][] = $table;
$tableSessionCount[$sessionNumber][$table] += 1;
break;
}
}
}
}
}
// convert 0 based table assignments to 1 based
array_walk($personTableAssignment, function (&$x) { $x = $x + 1; });
return $personTableAssignments;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment