What is the purpose of using a knapsack algorithm in PHP for a table reservation system?
The purpose of using a knapsack algorithm in a table reservation system is to efficiently allocate available tables to incoming reservation requests based on the capacity of each table and the number of guests in each reservation. This algorithm helps maximize the utilization of tables while ensuring that reservations are accommodated without overbooking.
// Knapsack algorithm implementation in PHP for table reservation system
function knapsack($capacity, $weights, $values, $n) {
$dp = array_fill(0, $n + 1, array_fill(0, $capacity + 1, 0));
for ($i = 1; $i <= $n; $i++) {
for ($w = 1; $w <= $capacity; $w++) {
if ($weights[$i - 1] <= $w) {
$dp[$i][$w] = max($values[$i - 1] + $dp[$i - 1][$w - $weights[$i - 1]], $dp[$i - 1][$w]);
} else {
$dp[$i][$w] = $dp[$i - 1][$w];
}
}
}
return $dp[$n][$capacity];
}
// Example usage
$capacity = 10;
$weights = [2, 3, 4, 5];
$values = [3, 4, 5, 6];
$n = count($weights);
echo knapsack($capacity, $weights, $values, $n); // Output: 11