Implement a weighted Round Robin algorithm (distributing requests across arrays according to their weights, for example 30%, 50%, 20%).
Asked at
AI answer
For distribution with a specified ratio, smooth weighted round robin is a good choice: rather than simply selecting the pool with the highest weight, it gradually balances the shares. The $current state must be preserved between requests.
function pickPool(array $pools, array $weights, array &$current): string
{
if ($pools === [] || array_keys($pools) !== array_keys($weights)) {
throw new InvalidArgumentException('Pools and weights must have the same keys');
}
$total = 0;
$selected = null;
$max = PHP_INT_MIN;
foreach ($weights as $key => $weight) {
if ($weight <= 0) {
throw new InvalidArgumentException('Weight must be positive');
}
$current[$key] = ($current[$key] ?? 0) + $weight;
$total += $weight;
if ($current[$key] > $max) {
$max = $current[$key];
$selected = $key;
}
}
$current[$selected] -= $total;
return $selected;
}
$pools = ['a' => ['...'], 'b' => ['...'], 'c' => ['...']];
$weights = ['a' => 30, 'b' => 50, 'c' => 20];
$current = [];
$key = pickPool($pools, $weights, $current);
Over a sufficiently large number of calls, the shares will be close to 30%, 50%, and 20%. With multiple PHP processes, each process has its own local state; if a single global distribution is required, store the state in a shared store, such as Redis, with atomic updates.
Also asked at Astrum Entertainment
- What is the difference between the equality operator '==' and the strict equality operator '===' in PHP?
- How can you perform binary search on a sorted array of infinite or unknown length (when the count function is unavailable)?
- Why is rounding (floor) used when calculating the midpoint, what other ways are there to remove the fractional part in PHP, and which is more optimized (the difference between a function and a language construct)?
- Implement binary search on a sorted array.
- What should a binary search function return if the target element is not found: -1 or an exception? Which is more appropriate?
Similar questions
- What is the time and space complexity of your implementation?
- Which design patterns have you used in real-world work, and in what situations?
- Which versions of PHP have you mainly worked with?
- PHP task: what will the `$user` and `$product` variables contain when the static method `getTableName()` is called in the `User` and `Product` subclasses? Explain your reasoning.
- What types of indexes in MySQL have you worked with?