Skip to content

Instantly share code, notes, and snippets.

@Gerst20051
Created August 17, 2015 22:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Gerst20051/08c5bdc970a0ee219092 to your computer and use it in GitHub Desktop.
Save Gerst20051/08c5bdc970a0ee219092 to your computer and use it in GitHub Desktop.
Permutation PHP Class
<?php
$permutation = new Permutation();
// $permutation = new Permutation(array_rand(range(0, 100), 4));
class Permutation
{
private $data = [];
private $permutations = [];
public function __construct($data = ['a', 'b', 'c', 'd'])
{
$this->data = $data;
$this->calculatePermutations();
$this->listPermutations();
}
public static function permutations(array $elements)
{
if (count($elements) <= 1) {
yield $elements;
} else {
foreach (self::permutations(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)
);
}
}
}
}
public function setData($data)
{
$this->data = $data;
}
public function calculatePermutations()
{
$this->permutations = [];
foreach (self::permutations($this->data) as $permutation) {
$this->permutations[] = $permutation;
}
}
public function listPermutations()
{
var_dump($this->permutations);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment