diff --git a/src/RandomIntegerAggregate.php b/src/RandomIntegerAggregate.php new file mode 100644 index 0000000..ba62439 --- /dev/null +++ b/src/RandomIntegerAggregate.php @@ -0,0 +1,39 @@ + + */ +final class RandomIntegerAggregate implements IteratorAggregate +{ + public function __construct( + private readonly ?int $seed = null, + private readonly int $min = 0, + private readonly int $max = PHP_INT_MAX, + ) {} + + /** + * @return Generator + */ + public function getIterator(): Generator + { + if (null !== $this->seed) { + mt_srand($this->seed); + } + + while (true) { + yield mt_rand($this->min, $this->max); + } + } +} diff --git a/src/RandomIterableAggregate.php b/src/RandomIterableAggregate.php index 48167d6..bee0151 100644 --- a/src/RandomIterableAggregate.php +++ b/src/RandomIterableAggregate.php @@ -25,14 +25,12 @@ public function __construct(private readonly iterable $iterable, private readonl */ public function getIterator(): Generator { - $cache = new CachingIteratorAggregate((new PackIterableAggregate($this->iterable))->getIterator()); - yield from new UnpackIterableAggregate( new UnpackIterableAggregate( new SortIterableAggregate( new MultipleIterableAggregate([ - new ShuffleIteratorAggregate(iterator_count($cache), $this->seed), - $cache, + new RandomIntegerAggregate(seed: $this->seed), + new PackIterableAggregate($this->iterable), ]), static fn (array $a, array $b): int => $a[0] <=> $b[0] ) diff --git a/src/ShuffleIteratorAggregate.php b/src/ShuffleIteratorAggregate.php deleted file mode 100644 index 79cc992..0000000 --- a/src/ShuffleIteratorAggregate.php +++ /dev/null @@ -1,44 +0,0 @@ - - */ -final class ShuffleIteratorAggregate implements IteratorAggregate -{ - public function __construct(private readonly int $max = PHP_INT_MAX, private readonly ?int $seed = null) {} - - public function getIterator(): Traversable - { - yield from $this->shuffle(range(0, $this->max - 1)); - } - - /** - * @param array $numbers - * - * @return array - */ - private function shuffle(array $numbers): array - { - if (null !== $this->seed) { - mt_srand($this->seed); - } - - for ($i = count($numbers) - 1; 0 <= $i; --$i) { - $j = mt_rand(0, $i); - [$numbers[$i], $numbers[$j]] = [$numbers[$j], $numbers[$i]]; - } - - return $numbers; - } -}