I found this function while I was looking for fastest way to find all possible permutations of numeric array.
private function permute(array $elements)
{
if (count($elements) <= 1) {
yield $elements;
} else {
foreach ($this->permute(array_slice($elements, 1)) as $permutation) {
foreach (range(0, count($elements) - 1) as $i) {
yield array_merge(
array_slice($permutation, 0, $i),
[$elements[0]],
array_slice($permutation, $i)
);
}
}
}
}
What I need is, to shuffle it's results and get random N permutations of a numeric array.
The problem is, it returns object and it's impossible to shuffle it's result.
Any sugestions? Any suggestions
This method returns an instance of Generator Class. And this is predictable as it uses
yield
instead ofreturn
. You can loop over this object withforeach
, or in your case you, can get the whole array of permutations withiterator_to_array
(this is possible because generator implements Traversable interface).Here is working demo.
You can read more about generators.