Skip to content

Commit

Permalink
Use this workaround
Browse files Browse the repository at this point in the history
  • Loading branch information
sanmai committed Nov 27, 2021
1 parent 4ad323a commit fb624ef
Showing 1 changed file with 10 additions and 2 deletions.
12 changes: 10 additions & 2 deletions src/Standard.php
Expand Up @@ -610,6 +610,14 @@ public function reservoir(int $size, ?callable $weightFunc = null): array
return iterator_to_array($result, true);
}

private static function drainValues(Generator $input): Generator
{
while ($input->valid()) {
yield $input->current();
$input->next();
}
}

/**
* Simple and slow algorithm, commonly known as Algorithm R.
*
Expand All @@ -631,7 +639,7 @@ private static function reservoirRandom(Generator $input, int $size): Generator
$counter = $size;

// Produce replacement elements with gradually decreasing probability
foreach ($input as $value) {
foreach (self::drainValues($input) as $value) {
$key = mt_rand(0, $counter);

if ($key < $size) {
Expand Down Expand Up @@ -663,7 +671,7 @@ private static function reservoirWeighted(Generator $input, int $size, callable
return;
}

foreach ($input as $value) {
foreach (self::drainValues($input) as $value) {
$weight = $weightFunc($value);
$sum += $weight;

Expand Down

0 comments on commit fb624ef

Please sign in to comment.