Getting random N permutations of numeric array using PHP

222 Views Asked by At

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

1

There are 1 best solutions below

0
On

This method returns an instance of Generator Class. And this is predictable as it uses yield instead of return. You can loop over this object with foreach, or in your case you, can get the whole array of permutations with iterator_to_array (this is possible because generator implements Traversable interface).

$permutations = iterator_to_array(permute($array));

shuffle($permutations);

$result = array_slice($permutations, 0, 3);

Here is working demo.

You can read more about generators.